Graphics Reference
In-Depth Information
Note that in the Start() function of the class (shown below), we use DontDestroyOnLoad
to keep this script and its gameObject alive even when new scenes are loaded. This means
we need to prevent duplicate scene managers being instanced, but we can easily use
GameObject.Find to have a look for a scene manager gameObject before instantiating a
new one.
public class SceneManager : MonoBehavior
{
public string[] levelNames;
public int gameLevelNum;
public void Start ()
{
// keep this object alive
DontDestroyOnLoad (this.gameObject);
}
The SceneManager.cs script provides a scene-loading function in its simplest form.
Here Application.LoadLevel is used to load a scene:
public void LoadLevel( string sceneName )
{
Application.LoadLevel( sceneName );
}
On top of simple scene loading, the class has support for a basic progressive level load-
ing game format. An array named levelNames holds strings referring to the names of each
of the levels in a game. We use an integer variable named gameLevelNum to refer to which
level the player is in. When GoNextLevel() is called, we do a quick check to make sure that
gameLevelNum is within range:
public void GoNextLevel()
{
// if our index goes over the total number of levels in the
// array, we reset it
if( gameLevelNum >= levelNames.Length )
gameLevelNum = 0;
Then, another version of the LoadLevel function (declared after this part) is called
to start loading the next scene based on the index number. Finally, gameLevelNum is
incremented, ready for next time. Note that the increment happens after the load and not
before. We could have done this either way, but this way, we have the minor inconvenience
of gameLevelNum always being one step ahead, which we need to be aware of if we ever try
to access its value from other classes. On the other hand, by incrementing it after the load,
we use GoNextLevel right from the start of the game to load the first level in the array,
keeping the code consistent in level loading:
// load the level (the array index starts at 0, but we start
// counting game levels at 1 for clarity's sake)
LoadLevel( gameLevelNum );
// increase our game level index counter
gameLevelNum++;
}
Search WWH ::




Custom Search