Singleton Pattern
Singleton Pattern
The Singleton pattern ensures that there is only one instance of a class throughout the
application. It is often used for managing global resources or components that should have a
single point of access, such as a game manager or an audio manager.
Explanation of the code:
private static SingletonClass instance; defines a private static variable to hold the
single instance of the class.
public static SingletonClass Instance is a public property that provides access to the
instance of the class. It uses a getter to retrieve the instance. If the instance is null, it
tries to find an existing instance of the class using FindObjectOfType. If no instance
is found, it creates a new GameObject, adds the SingletonClass component to it,
and assigns the instance to the created component. Finally, it returns the instance.
private void Awake() is a Unity callback method that is called when the object is
initialized. In this method, it checks if the instance is null. If it is null, it assigns the
current instance (this) to the instance variable and marks the GameObject as
persistent across scene loads using DontDestroyOnLoad(gameObject). If an
instance already exists, it destroys the current GameObject to enforce the Singleton
pattern.
By using the SingletonClass.Instance property, you can access the single instance of
the class from any part of the application. This ensures that there is only one
instance of the class throughout the runtime, making it a convenient way to
manage global resources or components that need to be accessed from multiple
locations.