To create the game manager functionality, we need a script to initialize a new scene and the state manager. We also need a second scene to be added to our project, to switch between scenes (named Home and Game). Another script is required to create a button that sends the application from the home scene to the game scene. Finally, we need a game object to attach the scripts to, which we are preserving as we switch between scenes. Let's get to work!
Scripts
folder in the Project panel and create a new C# script. Name the script StateManager
.using UnityEngine; using System.Collections; public class StateManager : MonoBehaviour { private static StateManager instance public static StateManager Instance { get { if(instance == null) { instance = new GameObject("StateManager").AddComponent<StateManager> (); } return instance; } } public void OnApplicationQuit() { instance = null; } public void StartState() { Debug.Log ("New scene is being created..."); } }
level_01
. As we haven't mentioned this before, we advise you to create a new folder in the Project panel before saving, and name it Scenes
. Use this folder to save the level_01
game scene and any other game scene you may create.home
.game_starter
from the Hierarchy panel.GameStarter
.lev_01
game scene at runtime. Add the following lines to the script:void OnGUI(){ if(GUI.Button(new Rect (120, 120, 150, 30), "Start Game")) { StartGame(); } }
In the previous piece of code, we call a StartGame()
function on pressing the button. We need to add this function to the script with the following lines:
void StartGame(){ print("starting game..."); DontDestroyOnLoad(StateManager.Instance); StateManager.Instance.StartState(); }
Now drag the GameStart script onto the GameStarter game object, inside the home scene of your project.
The home scene is the launching game screen of our prototype. The script attached to the GameStarter game object in the scene creates a button. Upon pressing this button, an instance of a game object with the StateManager
script is added to the scene. The DontDestroyOnLoad()
method takes care of preventing this script from being destroyed whenever we switch between game scenes.
State machines is a fascinating topic for anyone interested in science in general. For game developers, even more for AI developers, it is a must! We recommend digging into this matter, starting with http://en.wikipedia.org/wiki/Finite-state_machine.
18.117.78.237