Application LoadLevel() not working as expected

I have a quick prototype that I’ve whipped up in Unity but I’m having issues with scene transitions. I have a Game Scene and a Start Scene, akin to those flash game loading screens that have instructions or whatever. The issue I’m having is when I use Application.LoadLevel to load the game scene from the starting scene, game objects don’t seem to be initialized and my game crashes with null exceptions. When I run the game scene from the editor everything works fine. What am I doing wrong?

My code pretty much is this:

  if (GUI.Button(new Rect(100.0f, 50.0f, 100.0f, 50.0f), "Play Defending"))
        {
            GameController.clientColour_ = PlayerEnum.Blue;
            Application.LoadLevel("gameScene");
        }

        if (GUI.Button(new Rect(210.0f, 50.0f, 100.0f, 50.0f), "Play Attacking"))
        {
            GameController.clientColour_ = PlayerEnum.Red;
            Application.LoadLevel("gameScene");
        }

To have objects persist between scenes you need to use Application.LoadLevelAdditive. Your null reference exceptions are likely coming from GameController not persisting.

You have to wait till the next frame before you can access the loaded level objects and properties.

You can do that in a coroutine :

Enumerator LoadLevelRoutine(string levelName)
{
    Application.LoadLevel(levelName);
    yield return null; // let a frame pass

    // now you can access the scene objects and properties
}

Then, in your code, just do :

StartCoroutine(LoadLevelRoutine("my level"));

Here try this:

if (GUI.Button(new Rect(100.0f, 50.0f, 100.0f, 50.0f), “Play Defending”))

{

GameController.clientColour_ = PlayerEnum.Blue;

Application.LoadLevel(1);

}

if (GUI.Button(new Rect(210.0f, 50.0f, 100.0f, 50.0f), “Play Attacking”))

{

GameController.clientColour_ = PlayerEnum.Red;

Application.LoadLevel(1);
//in build settings look at the scene you want to load to and set the number of the scene to that loadlevel

}

that should work