My goal is to have a scene with all players already spawned and add a NetworkBehaviour to them when a client connects.
This is the NetworkManagerScript which inherits from NetworkManager:
public class NetworkManagerScript : NetworkManager {
[SerializeField] private Transform players;
private int currentPlayers;
public override void OnStartServer()
{
currentPlayers = 0;
}
public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
{
Debug.Log("OnServerAddPlayer: "+currentPlayers);
GameObject player = players.GetChild(currentPlayers).gameObject;
PlayerController playerController = player.AddComponent<PlayerController>();
playerController.PlayerNumber = currentPlayers++;
NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
}
}
On the NetworkManager I haven’t set a playerPrefab and the AutoCreatePlayer bool is set to true so that the OnServerAddPlayer is called automatically.
The PlayerController inherits from NetworkBehaviour, here is the code:
public class PlayerController : NetworkBehaviour {
[SyncVar(hook = "UpdateHP")] private int hp;
[SyncVar] private int playerNum;
private PlayerView playerView;
public int PlayerNumber
{
get { return playerNum; }
set { playerNum = value; }
}
[Command]
private void CmdAddHP(int hp)
{
this.hp += hp;
}
[Command]
private void CmdSubHP(int hp)
{
this.hp -= hp;
}
private void UpdateHP(int hp)
{
playerView.UpdateHP(hp);
}
private void Start()
{
playerView = GetComponent<PlayerView>();
}
private void Update()
{
if (!isLocalPlayer)
return;
if (Input.GetKeyDown(KeyCode.UpArrow))
{
CmdAddHP(1);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
CmdSubHP(1);
}
}
}
PlayerView code here:
public class PlayerView : MonoBehaviour {
[SerializeField] private Text hp;
public void UpdateHP(int hp)
{
this.hp.text = hp.ToString();
}
}
What this does is simply if I’m the localPlayer I can press either up or down button and the playerView will update the hp value. The thing is that I can do this just on the host, the components aren’t added on the clients’ scenes. When the first client connects these errors show, which I don’t understand:
[Warning]
Network configuration mismatch detected. The number of networked scripts on the client does not match the number of networked scripts on the server. This could be caused by lazy loading of scripts
on the client. This warning can be disabled by the checkbox in NetworkManager Script CRC Check.
[Info]
CRC Remote Dump PlayerController : 0
[Error]
OnObjSpawn netId: 1 has invalid asset Id
[Error]
OnObjSpawn netId: 2 has invalid asset Id
[Warning]
Did not find target for sync message for 2
All these messages are shown from UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()
This is a project to test the Unity Networking. I want to do a online card game inspired on Bang.