This content originally appeared on Level Up Coding - Medium and was authored by Mohamed Hijazi
When creating your project, you will encounter a case where you want to manage different player states, take control of the game’s audio, or for example, take control of loading scenes or controlling the UI.
Each one of these cases (and many more) can be put in a separate manager class. For example: GameManager, UIManager, AudioManager, etc.
Usually these manager classes are persistent through your game, and they would want to communicate with the different scripts in the game. You can get the gameObject instance holding these managers in each script you want to use them, but then you would fall into too many dependencies and your code might be prone to errors.
In order to achieve this, we can use a Singleton Pattern. This allows the Manager class to be easily accessible from other classes, and they get hold of the global variables and methods easily.
Singleton Pattern
In the manager class, first create a private static instance of the manager, and also create a public getter for this instance. Making it static will it to be accessed by other scripts. Finally in the Awake method, set the private instance to this manager class.
Now in order to access this manager class from other scripts, just call the public Instance.
GameManager.Instance.(your public variable or public method);
But having to type this singleton for every pattern can be tedious, so how can we streamline it?
We can create a separate script that holds the singleton code and then the manager classes can inherit this singleton class. So, create a C# Singleton Script.
Now when creating the manager class, simply inherit the Singleton script and you are all set, your manager class is now a Singleton
public class GameManager : Singleton<GameManager>
{
void Start()
{
}
void Update()
{
}
}
Tip of the Day: Manager Classes & Singleton Pattern in Unity was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Mohamed Hijazi
Mohamed Hijazi | Sciencx (2021-04-21T21:54:40+00:00) Tip of the Day: Manager Classes & Singleton Pattern in Unity. Retrieved from https://www.scien.cx/2021/04/21/tip-of-the-day-manager-classes-singleton-pattern-in-unity/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.