0

I'm relatively new to Unity, and decided to make a simple multiplayer game. After implementing the multiplayer aspect, two main problems arose. One, every person that joins will have n times the speed that they are supposed to have, where n is the number of players after the player joined. Two, I have a very simple camera script where it disables a camera if it isn't tied to the local player and enables it if it is. This doesn't work however, as everyone who joins can't connect to any camera and the host rapidly switches between the cameras.

Here is the code:

using Mirror;
using UnityEngine;

public class PlayerObject : NetworkBehaviour
{

    public GameObject playerPrefab;
    public KeyCode left;
    public KeyCode right;
    public float speed;
    GameObject myPlayerUnit;

    void Start()
    {
        if (isLocalPlayer == false)
        {
            return;
        }

        //Instantiate(playerPrefab);
        CmdSpawn();
        Debug.Log(myPlayerUnit == null);
    }

    void Update()
    {
        FindObjectOfType<Camera>().enabled = false;
        if (isLocalPlayer == false)
        {
            return;
        }
        CmdSetCamera(true);
        if (Input.GetKey(left))
        {
            CmdMove(false);
        }

        if (Input.GetKey(right))
        {
            CmdMove(true);
        }
    }
    [Command]
    void CmdSpawn()
    {
        GameObject go = Instantiate(playerPrefab);
        myPlayerUnit = go;
        NetworkServer.Spawn(go);
    }

    [Command]
    void CmdSetCamera(bool en)
    {
        if (myPlayerUnit != null)
        {
            myPlayerUnit.GetComponent<Camera>().enabled = en;
        }
    }

    [Command]
    void CmdMove(bool right)
    {
        if (myPlayerUnit == null)
        {
            return;
        }

        if (right)
        {
            myPlayerUnit.transform.Translate(speed, 0, 0);
        }
        else
        {
            myPlayerUnit.transform.Translate(-speed, 0, 0);
        }
    }
}

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Tyler Balota
  • 1
  • 1
  • 3
  • Hi! The current network system in Unity will be deprecated in the future. Maybe you can check 3rd party solutions for a network like Photon? – OnionFan Jun 27 '20 at 17:03
  • @OnionFan Mirror is a 3rd party network solution built around Unity's network code – Banana Jun 26 '21 at 14:59

1 Answers1

0

For the speed it looks like you are calculating it based on the player unit, and since the player units are messing with each other as you described with the cameras so you would want todo something like this

void Start() {
speed = 10f; //you need to define what your speed is or unity will calculate it weirdly
}

For the camera issue you should probably have the camera disabled in the prefab and enable it when the player joins