Search Unity

Question ClientRpc executs on the host but not on clients

Discussion in 'Netcode for GameObjects' started by KristenBoyGames, May 5, 2022.

  1. KristenBoyGames

    KristenBoyGames

    Joined:
    May 23, 2021
    Posts:
    38
    Code (CSharp):
    1.  
    2. // this method is triggered by a button only the host has
    3.     public void StartGameMethod()
    4.     {
    5.         if(NetworkManager.Singleton.IsServer)
    6.         isGameStartedClientRPC();
    7.     }
    8.  
    9.     [ClientRpc]
    10.     public void isGameStartedClientRPC()
    11.     {
    12.         Debug.Log("isGameStartedClientRPC udated");
    13.         N_isGameStarted.Value = true;
    14.         StartCoroutine("StartGame");
    15.     }
    16.  
    17.     }
    on the host side the "StartCoroutine("StartGame");" will trigger and start the game but the clients game will not.

    Edit: executes*
     
  2. Casual909

    Casual909

    Joined:
    Mar 3, 2021
    Posts:
    12
    I think you first gotta make a ServerRPC method and then call the ClientRPC method from there.
     
  3. edin97

    edin97

    Joined:
    Aug 9, 2021
    Posts:
    58
    hey, I don't know if you have "Error Pause" enabled in your console, but this code should pause your game on the client's side because a Client cannot change the value of a NetworkVariable, what I mean is that you wrote "N_isGameStarted.Value = true;" which I think is a NetworkVariable<bool> (?). Only the Host is allowed to change those NetworkVariable value. So this might be the reason your client doesn't trigger "StartCoroutine("StartGame");" (because after the error the client stops reading the next part of the code), try commenting the line 13 and see if it works that way.

    Also, to change a NetworkVariable (I know it's annoying) but you should call a ServerRpc() something like this :
    Code (CSharp):
    1.     [ServerRpc]
    2.     private void ChangeVariableServerRpc()
    3.     {
    4.         N_isGameStarted.Value = true;
    5.     }
    and call this when it's the client that need to change that variable, i.e, you can replace your line 13 by this :
    Code (CSharp):
    1. if (!IsServer)
    2. {
    3.    ChangeVariableServerRpc();
    4. }
    5.