Game Programming Pattern: Singleton
How to implement the Singleton Pattern in Unity
Objective: create a game manager script and use the singleton pattern.
Ok now I have to create a game manager for the great fleece. This script is going to have some functions and properties to control the state of the game.
In this script we have to create a private static variable of the same type of the script (in this case GameManager) and usually we call it _instance and also create a public property called Instance to allow other objects access to this instance.
By doing this we have only one instance of GameManager that can be accessed by any part of the game. This makes the communication between objects and the control of the state of the game.
To initialize the instance we have to use the Awake() function, check if the instance is null and assign instance = this. If for some reason you create another instance of a game manager the null check is going to avoid duplication and we are gonna keep only one instance of a game manager.
The last thing I added to this script is a property called HasKey, this is a bool that indicates if the player collected the key card. I am gonna use it in the other script to try the game manager.
So I created a new script called GrabKeyCardActivation and assigned it to the collider at the sleeping guard zone. Then I declared a variable to store the reference to the sleeping guard cutscene and by using the OnTriggerEnter function I just checked for the player tag and activated the object.
Then I created another script called WinStateActivation and assigned it to the collider at the end of the level.
In the script I created a reference to the win cutscene and by using again the OnTriggerEnter function I checked for the player tag and activate the win cutscene.
And that’s it!!! Basic use of the singleton Pattern.