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);
}
}
}