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.
QUESTION: Why does Start() gets called before Awake() gets called? This does not line up with the docs http://docs.unity3d.com/Manual/ExecutionOrder.