Issue setting player properties for other players on client side.
So I am making a small capture the flag game, and I am trying to get the other players on the clients to update their gameobject name and their material color. The actual variables are being set when I check the client player object, but its just the mesh renderer and actual name that won't set. My code is as follows.
[SyncVar]
public int team;
[SyncVar]
public string playerName;
[SyncVar]
public Color color;
Material mat;
public GameObject lobbyCam;
public GameManager gm;
void Start()
{
gm = GameObject.Find("_GameManager").GetComponent<GameManager>();
if (isLocalPlayer)
{
PlayerSetup();
}
NetworkSetup();
}
void PlayerSetup()
{
int team = Random.Range(0, 100);
if (team <= 50)
{
CmdSendPlayerInfo(0, "(Red)", gm.red);
}
else if (team > 50)
{
CmdSendPlayerInfo(1, "(Blue)", gm.blue);
}
}
[Command]
void CmdSendPlayerInfo(int teamNo, string newName, Color newColor)
{
Debug.Log("Team has been set for this player. Pushing to server.");
RpcUpdatePlayer(teamNo, newName, newColor);
}
[ClientRpc]
void RpcUpdatePlayer(int teamNo, string newName, Color newColor)
{
team = teamNo;
color = newColor;
this.GetComponent<MeshRenderer>().material.color = color;
playerName = "Player " + newName;
this.name = "Player " + playerName;
}
Essentially only clients and the players that connect to the server after them have their actual element properties set. The material colour and name of the players that were already on the server before the client do not have their properties set. It's probably really obvious, but I appreciate all the help and feedback I can get!
Answer by Sarrixx · Mar 03, 2018 at 04:13 PM
So it was a pretty obvious mistake (after hours of trying to figure out how to do it). Obviously PlayerSetup() is only called for the local player, so I fixed it as follows.
void Start()
{
gm = GameObject.Find("_GameManager").GetComponent<GameManager>();
if (isLocalPlayer)
{
PlayerSetup();
}
else
{
UpdatePlayer();
}
NetworkSetup();
}
And below are the changes I made to the RpcUpdatePlayer() function.
[ClientRpc]
void RpcUpdatePlayer(int teamNo, string teamName, Color newColor)
{
team = teamNo;
color = newColor;
playerName = "Player " + teamName;
UpdatePlayer();
}
void UpdatePlayer()
{
this.name = "Player " + playerName;
this.GetComponent<MeshRenderer>().material.color = color;
if (gm.debug)
{
Debug.Log("Player variables set. Name and material updated for " + this.name);
}
}
And everything seems to work nicely now!