Synchronizing Colors

A Code snippet to allow synchronization of colors from the server to clients

class ColorSync : NetworkBehaviour
{
    [SyncVar(hook="OnColor")]
    public Color myColor;

    void OnColor(Color newColor)
    {
        GetComponent<Renderer>().material.color = newColor;
        myColor = newColor;
    }

    public override void OnStartClient()
    {
        GetComponent<Renderer>().material.color = myColor;
    }
}
7 Likes

i tried the code but doesn work for me, server object dont update color in other clients

1 Like

It looks like you need an object on the server to set myColor for each client.

//In a NetworkManager-derived script
    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) {
        base.OnServerAddPlayer(conn, playerControllerId);
        GameObject player = null;
        PlayerController playerController = null;
        if (conn.GetPlayerController(playerControllerId, out playerController)) {
            player = playerController.gameObject;
        }
        if (player != null) {

            var playersyncer = player.GetComponent<ColorSync>();
            playersyncer.myColor = RandomEx.RandomColor();

        }

    }
1 Like

2017 update for @Oshroth 's code:

    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) {
        base.OnServerAddPlayer(conn, playerControllerId);
        if(conn.playerControllers.Count > 0){
            GameObject player = conn.playerControllers [0].gameObject;
            // do stuff to the player GameObject
        }
    }

This is assuming that you’ll only ever have 1 player per connection. If there are more, then just loop through the list…