Search Unity

SyncVar hook not being called by getter/setter

Discussion in 'Multiplayer' started by Deibu, Jun 30, 2015.

  1. Deibu

    Deibu

    Joined:
    Feb 24, 2013
    Posts:
    34
    I attached a hook to one of my SyncVars, but the function does not get called when I use a setter to change the variable. Is this a bug? Or am I just doing something wrong?
     
  2. CineTek

    CineTek

    Joined:
    Jul 12, 2013
    Posts:
    98
    Sometimes if you are setting the variables in your Start() function, they do not get updated. But maybe something is wrong in your implementation? Could you share some code pieces with us?
     
  3. Deibu

    Deibu

    Joined:
    Feb 24, 2013
    Posts:
    34
    Code (CSharp):
    1. if (Input.GetKeyDown (KeyCode.M))){          
    2.     workStation.Test = true; // this does not call the hook function
    3. }
    4. if (Input.GetKeyDown (KeyCode.N))){          
    5.     workStation.test = true; // this calls the hook function
    6. }
    7.  
    Code (CSharp):
    1. [SyncVar(hook="OnTest")]
    2. public bool test = false;
    3.  
    4. public bool Test {
    5.     get {
    6.         return test;
    7.     }
    8.     set {
    9.         test = value;
    10.     }
    11. }
    12.  
     
  4. shiva-js

    shiva-js

    Joined:
    Oct 5, 2011
    Posts:
    31
  5. peterept

    peterept

    Joined:
    Dec 6, 2012
    Posts:
    22
    From here:

    Note that setting a SyncVar member variable inside a property setter function does not cause it to be dirtied. Trying to do this will cause a compile time warning. Because SyncVars use properties internally to mark themselves as dirty, setting them dirty inside property functions could lead to recursion problems.

    Also, I note from using it that the hook function is only called if the variable value actually changes, so your keypress above setting it to true, would only fire the hook the first time KeyCode.M is pressed.
     
  6. seanr

    seanr

    Unity Technologies

    Joined:
    Sep 22, 2014
    Posts:
    669
    also that looks like client code.. you can only set syncvars on the server..
     
  7. Deibu

    Deibu

    Joined:
    Feb 24, 2013
    Posts:
    34
    I see. I just simplified my example so it was easier to read here, but that is good to know. Thanks!