Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

Question Adding A Player Mid-Game | Netcode for Gameobjects

Discussion in 'Netcode for GameObjects' started by FluffBear55, Apr 19, 2023.

  1. FluffBear55

    FluffBear55

    Joined:
    Mar 31, 2019
    Posts:
    2
    I've been struggling a lot lately with adding players to an existing server.

    Here is the code snippets I'm using. When a new player spawns, it's as if the server has been the owner of that player from the start.

    Code (CSharp):
    1.  
    2.  
    3. [SerializeField] private GameObject playerPrefab;
    4.  
    5. private void Singleton_OnClientConnectedCallback(ulong obj) {
    6.  
    7.         SpawnPlayerServerRpc(playerPrefab, obj);
    8.     }
    9.  
    10. [ServerRpc]
    11.     private static void SpawnPlayerServerRpc(GameObject playerPrefab, ulong clientID, ServerRpcParams serverRpcParams = default) {
    12.         GameObject playerTransform = Instantiate(playerPrefab);
    13.         playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(serverRpcParams.Receive.SenderClientId, true);
    14.     }
    15.  
     
  2. Ralfolas

    Ralfolas

    Joined:
    Mar 12, 2023
    Posts:
    5
    You need to pass that ulong client ID from OnClientConnectedCallback to SpawnAsPlayerObject. This is the ID of the client that has just connected.

    What you're currently doing is passing the client ID from the caller of the RPC, which doesn't make any sense here.

    But instead of making a ServerRPC, I would listen to the OnClientConnectedCallback on the server, and spawn the player object directly, like:

    Code (CSharp):
    1.     [SerializeField] private GameObject playerPrefab;
    2.  
    3.     private void Singleton_OnClientConnectedCallback(ulong newClientId) {
    4.         if(!IsServer) return;
    5.  
    6.         GameObject playerTransform = Instantiate(playerPrefab);
    7.         playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(newClientId, true);
    8.     }
     
  3. BennettFuel

    BennettFuel

    Joined:
    Oct 22, 2023
    Posts:
    2
    Is there any way to do this in which each player that connects has their unique player instantiated?