If your game passes the early prototype phase where you just use one scene and build the basic game mechanics, you might come to the point where you start building some test levels to check out some ideas and want to share them with friends, clients (or the world, I dunno).

Let’s say you keep your level selection screen and your game in different scenes (which I prefer to do), how do you pass the selected level id to the game scene where the appropriate data would then be loaded to build the level?

LevelSelection to game

DontDestroyOnLoad

There are different ways to share data between scenes.

You could use a GameObject with a MonoBehaviour script which keeps all attributes you want. You could then call DontDestroyOnLoad on your GameObject to prevent it from getting trashed once the scene is removed.

It could look something like this:

public class MyData : MonoBehaviour
{
  public int currentLevel = 0;

  void Start()
  {
    DontDestroyOnLoad(gameObject);
  }
}

Static attributes

But I think this is rather clunky and there is a much more elegant way to do this by using static class attributes. Static variables aren’t destroyed on scene changes and stay as long as the application is running. I prefer to use a single class called ApplicationModel which keeps things like current level or player data etc. An inheritance of MonoBehaviour isn’t necessary. All the data I’d like to keep available between scenes is placed in there as a static and public attribute.

public class ApplicationModel
{
  static public int currentLevel = 0;
}

The currentLevel attribute is updated after the necessary button at the level selection has been clicked. Subsequently the game scene get’s loaded by calling Application.LoadLevel(“MyGame”). After the scene has been loaded the currentLevel value is still available and the appropriate leveldata could be loaded right away.

Levelbutton script example

public class MyButton : MonoBehaviour 
{
  public int levelNr = 42;

  void OnMouseUp()
  {
    ApplicationModel.currentLevel = levelNr;
    Application.LoadLevel("MyGame");
  }
}

Game script example

public class MyGame : MonoBehaviour 
{

  void Start()
  {
    int levelNr = ApplicationModel.currentLevel;
    loadLevelData(levelNr);
  }

  void loadLevelData(int nr)
  {
    // load level data here
  }
}

Example & Source

A browser demo can be found here

The Unity3D project can be downloaded here 04-arrow-northeast