In-scene networkobjects aren't being spawned.

I’ve got a problem where I have a GameObject in my scene with a NetworkObject attached and want OnNetworkSpawn() to run when the GameObject spawns, which should be when the scene loads.


But nothing happens. I set a variable to tell me when the NetworkObject gets spawned, but it stays false even when I start host. I’ve tried turning on and off scene managment and creating a prefab of the GameObject and adding it to the NetworkPrefabs list, but no cigar.

Is this a bug or are NetworkObjects that are already placed within the scene before runtime not spawned automatically?

This should be spawned automatically. Check if the NetworkObject has been assigned a NetworkObjectId once the host has started.

What version of Netcode are you running?

The only odd thing I see is that you’re calling base.OnNetworkSpawn twice. What happens if you remove the one at the start of the OnNetworkSpawn method?

Do you use NetworkManager.Singleton.SceneManager to load this scene?

If not it means you must be using UnityEngine.SceneManager which leads to in-scene network objects not to spawn, and they also won’t synchronize with clients.

Or you may be using this scene as the first scene on entering playmode, which makes that scene non-networked as well.

Here’s what my best practice scene flow looks like:

That’s not the case, I have a networked game with only a single scene and it works fine. You need to have the NetworkManager in the scene and handle connections somehow (e.g. lobby) but the objects in the scene do spawn and synchronise correctly.

Okay, but that’s a very impractical, if not unusable setup.

What do you do when you want to restart the game? Loading a scene on the network with a NetworkManager already in is going to cause issues.

Right, it’s not practical for a real game and is really only viable for a prototype or test build. I was just correcting your statement that the first scene on entering play mode is automatically non-networked, that’s not the case. The first scene you enter can absolutely be networked and the in-scene placed networkobjects do get spawned and synced normally once you connect using the NetworkManager.

You’re right. I’ve observed that too. I think it used to be different in Netcode 1.1 but now you can even load (on the server side) a scene with UnityEngine.SceneManager and it will be synchronized - which is a bummer because now you have to implement callbacks to filter out scenes you don’t want synchronized.