Search Unity

Unity Multiplayer [SyncVar] GameObject problems - how to set a syncvar to null ?

Discussion in 'Multiplayer' started by mercior, Sep 27, 2016.

  1. mercior

    mercior

    Joined:
    Sep 21, 2015
    Posts:
    13
    Trying to understand the [SyncVar] in combination with GameObject.

    The idea is that objects in my game retain a reference to the player who owns them. I have a syncvar that points to the owning player.

    When a player disconnects, I was previously setting owner = null but this does not trigger the syncvar update hook. So - I made a global shared GameObject with a NetworkIdentity that I designate the 'null' object, instead. So now I can set owner = nullObject on the server which triggers the syncvar hook.

    But, when I set owner = nullObject I get some behaviour that I don't quite understand.

    Code (CSharp):
    1.  
    2.     [SyncVar(hook="_OnOwnerChange")]
    3.     public GameObject owner;
    4.     void _OnOwnerChange( GameObject newOwner ) {
    5.         owner = newOwner;
    6.  
    7.         Debug.Log("OnOwnerChange - owner = " + owner.ToString());
    8.         Debug.Log("OnOwnerChange - newOwner = " + newOwner.ToString());
    9.  
    10.         OnOwnerChange(); // done this way so OnOwnerChange can be overriddden!
    11.     }
    12.  
    With the result in the console:

    Code (CSharp):
    1.  
    2. OnOwnerChange - owner = mercior (UnityEngine.GameObject)
    3. OnOwnerChange - newOwner = NullObject (UnityEngine.GameObject)
    4.  
    I don't fully understand how the 2 variables can be different? This is in the console of a HOST that I am testing with (rather than a dedicated server) so perhaps I am seeing this message from the client-side rather than the server? And then the client can't set 'owner' because it is a syncvar??

    If so... is there any way I can get around this using a StartHost() setup? Is the SyncVar change hook called at all on the server? Its going to slow development for me a lot if I have to start building a dedicated server and client separately every time I want to test so I am trying to find a solution that will allow me to keep testing in the editor.
     
  2. mercior

    mercior

    Joined:
    Sep 21, 2015
    Posts:
    13
    After writing this I realized that owner == NullObject on the next frame so this is a race condition. I don't fully understand why its occurring yet but if I (lazily) invoke OnOwnerChange call on the next frame like this

    Code (CSharp):
    1. Invoke( "OnOwnerChange", 0 );
    Then I can safely check if owner == nullObject in the OnOwnerChange callback.

    I'd still appreciate anybody elses input into this behaviour and why it happens!
     
unityunity