Search Unity

Resolved Creating a custom player spawning script (Netcode for GameObjects).

Discussion in 'Netcode for GameObjects' started by darcypower, Jan 17, 2023.

  1. darcypower


    Jun 28, 2022
    How can i create a custom player spawning script (Netcode for GameObjects).

    I have a problem where I'm trying to spawn first person characters with different player models and also fix a problem where when a new player is spawned, all previous players see through the new players camera. If there's a way to solve this without writing a new player spawning script please let me know. but so far I thought that the best way for me to achieve this is to create a script called CustomNetworkManager that extends the NetworkManager script, the problem with this is i have no clue which function in the NetworkManager script is responsible for spawning players so i dont know which function to override.

    This issue seems like it would be pretty common for anyone trying to create a first-person game but i can't seem to find anything online about the issue except old UNet solutions, I was wondering if there is a different workaround that people are using instead of writing a customer player spawning script?

    Thanks in advance.
  2. RikuTheFuffs-U


    Unity Technologies

    Feb 20, 2020
    Hi @darcypower !

    Sure, you just need a NetworkVariable for this. You make the client send a ServerRPC to the server to pick the ID of the model, the server sets the ID in the NetworkVariable (synchronizing it across all clients) and then every client reacts to that update by getting the right model by ID for the player who selected it and showing it.

    You need to disable the camera on the prefab and enable it only when the local player joins. You can do this overriding OnNetworkSpawn in the NetworkBehaviour script you created to manage your players.

    Code (CSharp):
    1. public override void OnNetworkSpawn()
    2.     {
    3.         base.OnNetworkSpawn();
    4.         if (!IsOwner)
    5.         {
    6.             //disable camera & inputs
    7.             m_Camera.enabled = false;
    8.             //...
    9.             return;
    10.         }
    11.        //enable camera & inputs
    12.         m_Camera.enabled = true;
    13.         //...
    14.     }
    If you look at the ClientDriven sample, you can see how inputs, cameras and so on are enabled/disabled on the local player.

    Does this help?