1️Singleton

What's that?

The Singleton Design Pattern is a design pattern used to guarantee that a class has only one instance, as well as granting global access to that instance. This is useful when there is a need to ensure that only one instance of a class is used in the entire application.

In video game development, the Singleton Design Pattern can be used to manage game loops, audio engines, or input systems. In addition, the Singleton Design Pattern can also be used to manage access to limited resources, such as databases or file systems. By using Singleton, we can ensure that there is only one instance of a class that manages the resource, so there are no access conflicts or race conditions when the resource is being used by more than one class.

However, there are some drawbacks to the Singleton Design Pattern. First, Singleton cannot be used in cases where a class must have more than one instance. Second, Singleton has tight coupling with other classes, so it will be difficult to change its implementation to other classes without changing the existing code.

Pros

  • Can be sure that a class has only one instance.

  • Can grant global access to the instance.

  • The singleton object is initialized only when it is requested for the first time.

Cons

  • Overuse worsens the architecture, for example, when program components know too much about each other.

  • It can be difficult to use Unit Testing when using Singleton because many test frameworks rely on inheritance when creating mock objects.

Implementation

To turn a class into a singleton, you can simply inherit from the Singleton class Singleton<T>

public class MyClass: Singleton<MyClass> { }

If you need a function that is executed when the singleton instance is created, you can override OnCreate(), likewise if you want something to happen when the singleton is destroyed you can override OnDestroy()

public MyClass : Singleton<MyClass>
{ 
    protected override void OnCreate()
    {
        base.OnCreate();
        // This is executed only once when created automatically
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        // This is executed only once when destroyed
    }
}

By default, a singleton class will be a GameObject that persists when switching scenes. This means that the GameObject will always be there even if you switch scenes. If you don't want this behavior, you can override the IsPersistBetweenScenes Properties to false

public MyClass : Singleton<MyClass>
{ 
    protected override bool IsPersistBetweenScenes => false;
}

If the singleton class is not in the scene, then when another script calls the singleton reference, a new GameObject will be formed with the singleton component before finally returning the reference.

Last updated