Search Unity

Synchronizing Colors

Discussion in 'Multiplayer' started by seanr, Jun 20, 2015.

  1. seanr

    seanr

    Unity Technologies

    Joined:
    Sep 22, 2014
    Posts:
    669
    A Code snippet to allow synchronization of colors from the server to clients


    Code (CSharp):
    1.  
    2. class ColorSync : NetworkBehaviour
    3. {
    4.     [SyncVar(hook="OnColor")]
    5.     public Color myColor;
    6.  
    7.     void OnColor(Color newColor)
    8.     {
    9.         GetComponent<Renderer>().material.color = newColor;
    10.         myColor = newColor;
    11.     }
    12.  
    13.     public override void OnStartClient()
    14.     {
    15.         GetComponent<Renderer>().material.color = myColor;
    16.     }
    17. }
    18.  
     
  2. wicked208

    wicked208

    Joined:
    Oct 25, 2010
    Posts:
    83
    i tried the code but doesn work for me, server object dont update color in other clients
     
    christophermrau likes this.
  3. Oshroth

    Oshroth

    Joined:
    Apr 28, 2014
    Posts:
    99
    It looks like you need an object on the server to set myColor for each client.
    Code (CSharp):
    1.  
    2. //In a NetworkManager-derived script
    3.     public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) {
    4.         base.OnServerAddPlayer(conn, playerControllerId);
    5.         GameObject player = null;
    6.         PlayerController playerController = null;
    7.         if (conn.GetPlayerController(playerControllerId, out playerController)) {
    8.             player = playerController.gameObject;
    9.         }
    10.         if (player != null) {
    11.  
    12.             var playersyncer = player.GetComponent<ColorSync>();
    13.             playersyncer.myColor = RandomEx.RandomColor();
    14.  
    15.         }
    16.  
    17.     }
     
    christophermrau likes this.
  4. lexi89

    lexi89

    Joined:
    Dec 5, 2016
    Posts:
    4
    2017 update for @Oshroth 's code:

    Code (CSharp):
    1.     public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) {
    2.         base.OnServerAddPlayer(conn, playerControllerId);
    3.         if(conn.playerControllers.Count > 0){
    4.             GameObject player = conn.playerControllers [0].gameObject;
    5.             // do stuff to the player GameObject
    6.         }
    7.     }
    This is assuming that you'll only ever have 1 player per connection. If there are more, then just loop through the list...