Using singletons in Unity
A singleton is a design pattern that ensures that only one instance of it exists. This can be useful for objects that are instantiated once such as GameManager class.
Here’s a basic creation of a singleton that manages one boolean property HasCard:
To access it from the outside you can simply access it from the public and static Instance variable. This means, you need not instantiate this class at all with the new operator.
Here’s an example of setting the property of the single object:
Here’s an example of getting the property of the single object:
One big disadvantage of using a singleton is that you need to property of Inspector to debug to see its contents:
Other than that, the option that you can ensure that the class can only be instantiated once is still beneficial.