class MyManager : NetworkManager
{
public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
{
GameObject player = (GameObject)Instantiate(playerPrefab, Vector3.Zero, Quaternion.Identity);
player.GetComponent<Player>().color = Color.Red;
NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
}
}
It works fine, player prefab got red color, but on the host side only. Any clients which connect to the game do not see any changes in player’s prefab.
Hello,
The thing is that the function NetworkServer.AddPlayer does not have to be called from within OnServerAddPlayer. As long as the correct connection object and playerControllerId are passed in, it can be called after OnServerAddPlayer has returned. This allows asynchronous steps to happen in between, such as loading player data from a remote data source.
Not sure if you still need an answer to this or not, but I was having similar problems with my program, where pressing the space bar was supposed to change the color of the player object.
To solve this, I had to use the [Command] and [ClientRpc] tags and have two separate methods doing the coloring. Here’s a snippet of my code. Hopefully it helps.
void Update(){
if (!isLocalPlayer){
return;
}
if (Input.GetKeyDown(KeyCode.Space)){
CmdColorChange(transform.gameObject, currentColor);
}
}
[Command]
void CmdColorChange(GameObject obj, Color toChange){
RpcColorChange(obj, toChange);
}
[ClientRpc]
void RpcColorChange(GameObject obj, Color toChange){
obj.GetComponent<MeshRenderer>().material.color = toChange;
}
Basically, the [Command] tag means that method is only called on the server, while [ClientRpc] means the method is only called on the clients. For whatever reason, changing the color just on the server (which I imagine is where OnServerAddPlayer() is called) doesn’t change it on any of the clients, so the server has to then tell the clients they also need to change the color, via a [ClientRpc] method.
One note: if you use a [Command] or [ClientRpc] tag, the method names have to have either Cmd or Rpc at the beginning, or they won’t work.