Day 81: Creating Manager Classes in Unity
Objective: Create a Game Manager class.
Each manager class we will create will use the pattern called Singleton. This allows for one instance of an object to be in the game and allow for another class to call the object without using GetComponent.
Our Game Manager class will need to allow the player to skip the starting cutscene and save a bool that the player has the keycard.
To start we will need a game object that will hold the manager class.
Now we need an variable to hold the cutscene game object. But since we are not activating the cutscene but having it skip to the end. To start we need to get the libaray that holds the PlayableDirector. We need to add “using UnityEngine.Playables;”
Now let’s add a variable to hold the object.
Now in Update we will need to check for input from the player and taking the introcutscene time to 59.45f, which is right before the ending of the cutscene.
Now the skipping of the scene is done, let’s move on to the bool so the player can win the game. To start, let’s create a singleton pattern. The first thing we need is a static GameManager instance. We will create a private and public GameManager Instance. The private is just for this class and the public is so other classes can call this.
For our public Instance, we need to create a property that gets an instances. It will check to see if the private instance is null, if it is rely an error. If not, it will return the private instance.
Now to set this object as the instance, we’ll use Unity’s Awake function to set the private instance to this object.
Before we move to other scripts to use this instance, we’ll create a bool that uses a properties to set the bool.
Now this is set up, save this script and let’s move to our GrabKeyCardActivation script. Unlike other objects where we use GetComponent to use a script off an object, we can just call the manager instance and use any public variables in it, as seen below.
Since we use the instance to set the bool to true, we can move to our ending cutscene to check and see if the bool is true and if it is play cutscene, if not ignore the player.
That is how we can use a manager class to handle some states of the game.
Thank you for reading and have a wonderful day!