Today we will take a look how to implement simple Level manager into our game
Lets start by crating new C# Script. And create few simple methods inside it.
We will use 2 libraries and inherent from MonoBehaviour.
It’s important to add all of our scenes to build settings(File->Build Settings) before we can use our manager.
using UnityEngine; using System.Collections; public class LevelManager : MonoBehaviour { //We will use this public parameter in one of our methods //Its public so we can change it in inspector public float autoLoadNextLevelAfter; // Here we create few methods as an example //This one loads next level after 2s void LoadNextLevelAfterFixedTime(){ Invoke("LoadNextLevel", 2f) } //We can pass the time value to our method public void LoadNextLevelAfter(int time) { Invoke("LoadNextLevel", time); } // Here is another method where we can load level by // it number in build settings(ctrl+Shift+B) public void LoadLevelByNumber(int levelNumber) { Application.LoadLevel(levelNumber); } //I'm finding this one very useful. It loads the scene by its name public void LoadLevel(string name) { Application.LoadLevel (name); } // This one calls quit request. public void QuitRequest(){ Debug.Log ("Quit requested"); Application.Quit (); } //Loads next level in build order, can be useful in platform games public void LoadNextLevel() { Application.LoadLevel(Application.loadedLevel + 1); } }
You can use this script in many different ways. We will create simple demonstration by loading next level when button is clicked.
Now lets add our script to button game object on the scene
here we drag our button from the scene, and we chose method we want to use —>
We attach the script itself to the game object. We can set our time property here
This in only one way of doing it. In more complex projects it’s recommended to crate empty game object on the scene where we store our script, and refer to it every time we want to use it method.
Here is another example i used recently
void OnLevelWasLoaded(int level) { if (level == 2) { Achievment.A_1 = true; Debug.Log(Achievment.A_1); }
We can use methods like this to handle operations performed on levels.
Managers like this can be really helpful when we create large projects, this way we can produce easy to understand code and we don’t need to repeat the same code in every place where we need to make operation related to levels or scenes. We can handle conditions or events that can appear during the game.
I hope this article was helpful to you. Next time I will introduce another great method of unity games development, but till than… Stay Awesome!