unity-game-enginemultiplayerunity3d-mirror

Multiplayer UI using Mirror unity


im pretty new to the mirror package and im trying to build a simple multiplayer game thats basically played using UI elements only (buttons). A big part of the game is announcements that show up like - "Player X's Turn" for example.

At the moment the announcement only shows up in the host game, if the announcement came from the Networkbehaviour class that belongs to the player it would be easy to solve with a simple ClientRPC function but i want the UI functions to run from a different class that handles the UI elements.

what is the correct way to implement this? does the UIHandler need to be inhereting from any network class? would love some tips regarding this subject.

thanks in advance, Amit Wolf.


Solution

  • A common strategy is to build a singleton networked event manager that triggers the RPC as an event.

    public class EventManager: NetworkBehaviour
    {
        public static EventManager Instance;
    
        
        void Awake()
        {
            if(Instance == null)
                Instance = this;
            else
                Destroy(this);
        }
    
        public event Action<int> OnPlayerTurnChanged;
        
        [ClientRpc]
        public void ChangeTurn(int playerId)
        {
            OnPlayerTurnChanged?.Invoke(playerId);
        }
    }
    

    Then you can subscribe to the event in any other script and perform logic:

    public class UIScript: NetworkBehaviour
    {    
        void Awake()
        {
            EventManager.Instance.OnPlayerTurnChanged+= UpdateUI;
            timer = 0f;
        }
    
        void UpdateUI(int playerId)
        {
            //UI Logic to set the UI for the proper player
        }
    }