Using Singletons & Static Variables To Create Manager Classes In Unity

The “Static” keyword is added to a variable or class in order to make it accessible from within any other class. By making something “Private” and “Static” you are adding it to a memory bank for it to be seen by other classes, but preventing other classes from being able to directly reassign it to equal something else. Though a “Public/Static” variable can call on a “Private/Static” variable that is declared within the same class, even from outside of the original class.

A “Singleton” is a “Programming Design Pattern” that allows you to access a specific class directly without using something like “Get Component”. Singletons are used when creating a reference to a unique class and ensures that the class only exists once. These are particularly useful when you are creating Manager type classes such as a UI Manager or Game Manager. A Singleton has roughly the same pros and cons as a global variable and although they’re super-handy, they can break the modularity of your code.

Singleton Classes can be used to communicate with other Singleton Classes, but otherwise should only ever be communicated with, and NOT be the one trying to communicate.

You can now access this script and any of its public methods from any other script by simply using the line of code in the example below!

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!