Search Unity

Resolved Updating Variables

Discussion in 'Netcode for GameObjects' started by Momissimo, Nov 25, 2022.

  1. Momissimo

    Momissimo

    Joined:
    Aug 15, 2019
    Posts:
    18
    I have an issue regarding updating variables across the Host and the Clients. So i want to know how many players have joined a server that the Host has created. I have a class called PlayersNetworkManager that inherits from NetworkBehaviour. Once i join as a Client or as a Server the Start method of this classed is triggered and the public NetworkVariable<int> playersInGameText increases. Additionaly i update (through a delegate) the TextMeshProUGUI varibale (this belongs to another class). Now, only Server displays the correct number. The only solution that i found is to use the Update method to keep looking at the value of the public NetworkVariable<int> playersInGameText and update the TextMeshProUGUI variable accordingly, this works. But i would like to avoid using the Update function as much as possible. Any suggestion?
     
  2. cerestorm

    cerestorm

    Joined:
    Apr 16, 2020
    Posts:
    666
    You can subscribe to the network variable's OnValueChanged callback so you can run your own code when the value changes. https://docs-multiplayer.unity3d.co...orkvariable/index.html#onvaluechanged-example. You might also need to have the same code run in OnNetworkSpawn in case the network object spawns with the latest network variable value as it won't trigger OnValueChanged.

    On the server you can check your count is correct by comparing it to NetworkManager.Singleton.ConnectedClientsIds.Count.
     
    Momissimo likes this.
  3. Momissimo

    Momissimo

    Joined:
    Aug 15, 2019
    Posts:
    18
    Thanks a lot!!!
     
    cerestorm likes this.