Search Unity

Quick question about SyncVar and inventory

Discussion in 'Multiplayer' started by errandfox, Dec 27, 2016.

  1. errandfox

    errandfox

    Joined:
    Apr 22, 2015
    Posts:
    42
    Just wondering, why would inventory items need to be synced to all other players?? If my local player has items in his inventory, the remote players don't need to know that, only the server/host does, to check/allow items being used.
    I can just use cmd and rpc to keep track of local player inventory - as in for server to auth pickups/usage and anti cheat?
    Or am I misunderstanding SyncVars?
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,508
    SyncVars take the Server value of the variable and force it upon the Clients.

    If the server is authorative and you're using a SyncVar for each item in the inventory you're probably wasting a lot of bandwidth. A better way might be to have the Server give the client a base state of their inventory, then when the client does something that will change the inventory it goes through the server, the server approves/denies and sends the command to do it on the client.

    Code (csharp):
    1.  
    2.                         // for this client
    3.         public virtual void DropItem()
    4.         {
    5.             CmdDropItem();
    6.         }
    7.  
    8.         [Command]       // for the server
    9.         public virtual void CmdDropItem()
    10.         {
    11.             if (!canDropItem) return;
    12.             RpcDropItem();
    13.         }
    14.  
    15.         [ClientRpc]     // for the other clients
    16.         public virtual void RpcDropItem()
    17.         {
    18.             StartCoroutine(ActuallyDropItem());
    19.         }
    20.  
    Something like that is what I mean. Its really vague, but I think you kinda get the idea.

    Here's some general notes I wrote down for myself.

    Code (csharp):
    1.  
    2. // Notes:
    3. // [Command] is for a CLIENT telling the SERVER to run this method.
    4. // [ClientRpc] is for a SERVER telling ALL CLIENTS to run this method.
    5. // [Server] means the code can only be run on the SERVER.
    6. // [SyncVar] forces the SERVER value of the variable to ALL CLIENTS.
     
    Last edited: Dec 27, 2016
  3. errandfox

    errandfox

    Joined:
    Apr 22, 2015
    Posts:
    42
    That's fantastic, thankyou, and what I suspected. That makes perfect sense.
    I'm coming over from photon pun to unet as I think I've wrapped my head around photon quite well but think that Unet will be the way for me going forward. This is going to be a pleasure I can see now :)