Game Programming Pattern: Singleton
Stealth Game & Cinematography
Objective: Use Singleton pattern to create a Game manager
We already created the gameobject and stored the script with the same name inside it. Now lets write some code
Now inside the GameManager script, we create a static variable of same type as the script class and set it as private so that you cannot directly access the variable from outside the script.
Then create another public static variable of static type but define only the get properties so that other script can get access to this script _instance values but not change it by using only the get properties.
Then store the script inside the _instance as soon as the gameobejct is initialized using Awake.
Now with this you can easily access any public variables and methods inside this script.
To see how it works, lets create a function to change the bool value which tells if the card is stolen or not. So, create a HasCard bool and set its properties to both get and set so that other script can access and modify its values.
Now after player triggers the steal card cutscene, we can change the bool value of HasCard to true so we can do by calling the public instance variable using ScriptName.Instance(GameManager.Instance) which works same as when you accessed the script and now you can access all the public variables and methods. Here, we changed the value of HasCard to true.
And we can do the same from other scripts also. here we are checking the value of HasCard so that only when it is true, player wins the game after trigger.
Now, the question is how can we do this? The answer is simple, Its because we are defining the variable as static which stores itself in a special place accessible by all without needing to find it. Its just like when you need some food, you can look into the fridge which is easily accessible to everyone and doesn’t need to call others to find. But if the food is not stored inside the fridge then you need to contact the supplier or call others for help. In our case, we can get all the variables and methods inside the manager but we still need to call other scripts for values if not available in manager class.