PlayerObject spawning AFTER OnClientStarted gets called

I have an in-scene object that needs to access the camera of the local PlayerObject, once it has spawned.
Inside the start method of said object, i have the following code:

NetworkManager.Singleton.OnClientStarted += () => {
           
    print(NetworkManager.Singleton.LocalClient.PlayerObject); // This is null in the clients
           
    _mainCam = NetworkManager.Singleton.LocalClient.PlayerObject.GetComponentInChildren<Camera>();
    _portalCam.projectionMatrix = _mainCam.projectionMatrix;
};

This works fine on the host, and everything initializes as expected, but for clients joining, the local PlayerObject is null here. It does eventually spawn, but thats after OnClientStarted has been called. According to the documentation it should be called “once the local client is ready” (Event OnClientStarted | Netcode for GameObjects | 1.7.1).

Shouldnt OnClientStarted only be called after the local player object has been set up, or am i mistaken?
If not, does anyone know why its being called before the player has spawned in? Or what other callback i can use?

NetworkManager.OnClientStarted is invoked when the NetworkManager has finished starting as a client but does not mean that everything is spawned. With a host, it will invoke both NetworkManager.OnServerStarted and NetworkManager.OnClientStarted. The host works because the host handles the client approval immediately during the NetworkManager startup.

I would recommend using the NetworkManager.OnClientConnectedCallback to handle spawn dependent actions.
NetworkManager.OnClientConnectedCallback is invoked after the client has:

  • Been connected and approved

  • If scene management is enabled:

  • Loaded all required scenes and spawned and synchronized all NetworkObjects.

  • If scene management is disabled:

  • Spawned and synchronized all NetworkObjects.

2 Likes