NullReferenceException when referencing a NetworkBehaviour

I have a pretty interesting problem.
NetworkBehaviours require a NetworkIdentity component. Not a problem actually. But when I add the NetworkIdentity component to the gameobject and I want to access the NetworkBehaviour class via GameObject.Find(“…”).getComponent<…>, I always get a NullReferenceException.

Has anyone a solution for this problem?

First, can you break up the expression to determine which part is returning null.

var myObject = GameObject.Find("...");
if (myObject == null) {
    Debug.LogError("Could not find game object.");
} else {
    var myComponent = myObject.GetComponent<...>();
    if (myComponent == null) Debug.LogError("Could not get component");
}

Looks like the object is always disabled when entering playmode so the “missing” object causes the NullReferenceException. But why is this happening?

From the docs:

You can read more here: https://docs.unity3d.com/Manual/UNetSceneObjects.html

But the strange thing is that it already worked well once but then the game decided to not work anymore.
Mh…

EDIT: NetworkServer.SpawnObjects() isn’t even working. Wtf is up today?

Yeah, trying to figure out why it’s not working can get pretty frustrating!

One thing to check: Make sure NetworkIdentity components are only on root game objects (not child objects).

There’s more info here: https://docs.unity3d.com/ScriptReference/Networking.NetworkIdentity.html

I’ve read a lot about the networkingsystem but I still can’t figure out why it doesn’t work. NetworkServer.SpawnObjects() doesn’t give out an exception, the objects definitely have a NetworkIdentity component attached and the function is called. I wonder why it still doesn’t work.