Setting up a simple game manager in Unity
Most games will need a game manager to keep track of the progress in the game. Let’s go over how create it.
First, create the game object that will hold the GameManager script. Create the script and attach to the game object. When you create a script with this name Unity will automatically change the icon to a cog wheel:
Open up the script. To make the class easy to access and make sure that there is only one instance of the game manager, we will use a programming pattern called Singleton. To ensure that we limit access, we will use a public property instead of a public variable:
We check if another game manager has already been added to the scene in the Awake function. If another game manager exists, destroy that game object. If no other game manager exists, initialize the instance to itself. As a game manager needs to exist throughout all scenes, call the function DontDestroyOnLoad:
With a game manager it is recommended that you use public properties instead of variables to have better control over access:
Once the Singleton pattern has been set up there will be very little reason to change anything. To make it tidier you can put the code within a region and then minimise this: