Help Needed!! sync inventory updates for players

Hi im trying to update each player’s inventory each time they colliding with a collectible game object,
so far the variable i assinged to count the collectibles is syncing perfectly but i cant update the ui text which showes the counter on screen.
this is the inventory handler script for now:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System;

public class InventoryHandler : NetworkBehaviour {

    public Text airSlotText;

    [SyncVar]
    public int airCapsulesInInventory = 0;
    public NetworkIdentity myNetId;

    // Use this for initialization
    void Start () {

        airSlotText.text = "X " + 0;

    }

    // Update is called once per frame
    void Update () {

    }

    private void OnCollisionEnter(Collision collision)
    {
        if (!myNetId.isLocalPlayer)
            return;

        if (collision.gameObject.tag == "airToken")
        {
            CmdChangeCapsulesAmount(airCapsulesInInventory+1);
        }

    }

    [Command]
    public void CmdChangeCapsulesAmount(int num)
    {
        airCapsulesInInventory = num;
       // airSlotText.text = "X " + airCapsulesInInventory;

        RpcUpdateInventory(num);
    }

    [ClientRpc]
    public void RpcUpdateInventory(int num)
    {
        if (myNetId.isLocalPlayer)
            airSlotText.text = "X " + num;


    }
}

actually the ui text showes the correct amount only at the last looged in player.

You should probably implement a hook function in which you update the display of objects based on the current/new value of the syncvar, and then you use OnStartLocalPlayer to set default values, and OnStarClient to synchronize the display for newly joining players. The hook isn’t automatically called for new players.

This post here has a working implementation Simple SyncVar test, not updating when running as client

got it!! I actually had to add this code to the start function:

    private void Start()
    {
        if (myNetId.isLocalPlayer)
            InventoryCanvas.enabled = true;
        else
            InventoryCanvas.enabled = false;

    }
1 Like