Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on Dec 8, 2022, between 7 am & 7 pm EST, in the DOTS Dev Blitz Day 2022 - Q&A forum, Discord, and Unity3D Subreddit to learn more about DOTS directly from the Unity Developers.
    Dismiss Notice
  3. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

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:
    29
    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:
    1,619
    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:
    29
    Yep, exactly what i though. Thanks! <3