Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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?