Search Unity

Resolved Looking for best practices with Server RPC

Discussion in 'Netcode for GameObjects' started by joan_stark, Nov 16, 2022.

  1. joan_stark

    joan_stark

    Joined:
    Jul 24, 2018
    Posts:
    43
    I'm working on 1vs1 card game, and my question is:
    When players join the game, I call the function RegisterPlayerServerRpc, so the server registers the player and saves its clientId. When 2 players have registered it starts the game.
    Now here comes the question. Should the function StartGame be an rpc, or should it be a normal function? What's the difference in any case?

    Code (CSharp):
    1.  
    2. [ServerRpc(RequireOwnership = false)]
    3. private void RegisterPlayerServerRpc(ServerRpcParams serverRpcParams = default)
    4. {
    5.     Debug.Log($"Registered player: {serverRpcParams.Receive.SenderClientId}");
    6.     _playersRegistered.Add(serverRpcParams.Receive.SenderClientId);
    7.    
    8.     if(_playersRegistered.Count >= 2)
    9.         StartGame(); // or StartGameServerRpc
    10. }
    11.  
    12. private void StartGame()
    13. {
    14.     Debug.Log("Start Game");
    15. }
    16.  
    17. [ServerRpc]
    18. private void StartGameServerRpc()
    19. {
    20.     Debug.Log("Start Game");
    21. }
    StartGame function is meant to start all the logic behind the gamemode like randomly select the first player to start, send to the clients whoever starts, etc...

    Thanks <3!
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    6,005
    Not an RPC method because you are already running it only on the server by calling it from a ServerRpc method and you probably don‘t want to give any player the ability to start the game on the server side.

    StartGame() can then change NetworkVariable or call ClientRpc as needed to get the game started.
     
    RikuTheFuffs and joan_stark like this.
  3. joan_stark

    joan_stark

    Joined:
    Jul 24, 2018
    Posts:
    43
    Yep, exactly what i though. Thanks! <3