2
\$\begingroup\$

I made a little game in Unity. It works fine in the Editor. But if I run the build version I get a NullReferenceException.

This problem does only appear if the build-version-client hosts the game.

  • No problems if the BUILD-version plays as client or server only.
  • No problems when played in EDITOR

I have a class (CharacterSpawner) that is meant to run on the server only.

public static CharacterSpawner instance;

...

public void Awake()
{
    instance = this;
    print("Character Spawner Awake");
}

[Server]
public void SpawnCharacter(NetworkConnection owner)
{
    GameObject character = Instantiate(characterPrefab, randomSpawnPoint, Quaternion.identity) as GameObject;
    NetworkServer.SpawnWithClientAuthority(character, owner);
}

I have another class (Player) that should send a Command to the server in order to spawn a character right at the beginning.

void Start()
{
    if (isLocalPlayer)
    {
        CmdSpawnCharacter();
    }
}

[Command]
public void CmdSpawnCharacter()
{
    CharacterSpawner.instance.SpawnCharacter(connectionToClient); // throws NullReferenceException
}

'instance' is here the only thing that could cause the NullReferenceException, because connectionToClient would not cause a NullReferenceException even if it was null! This means the instance is not set yet.

As problem I can think that the Start-method in the Player-script is called before the Awake-method in the CharacterSpawner Script. Because if I call CmdSpawnCharacter like this:

Invoke("CmdSpawnCharacter", 0.5f);

It works perfectly, but that is not the way I want to do this.

I even changed the priorities of the scripts, but without success. enter image description here

QUESTION: Why does Start() gets called before Awake() gets called? This does not line up with the docs http://docs.unity3d.com/Manual/ExecutionOrder.

\$\endgroup\$
2
\$\begingroup\$

I'm having similar issues with UNET calls running in a different order in the Editor vs in a build.

The reason your issue is happening is that networked scene objects are turned off when an online scene first loads, and Awake won't run until the object is enabled. For whatever reason these objects seem to get enabled slightly later in a build than they do when running in the editor, hence why Awake hasn't run yet in this case.

It's not a solution, but hopefully that explanation will help you come to one!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.