MonoBehaviour Singletons

The Singleton pattern is often used overused abused in Unity to take advantage of its global access properties. I find it is usually better practice to address those requirements through other means. However, that still leaves the common and legitimate need for enforced singularity.

// --------------------------------
// <copyright file="SingletonMonobehaviour.cs" company="Rumor Games">
//     Copyright (C) Rumor Games, LLC.  All rights reserved.
// </copyright>
// --------------------------------

using UnityEngine;

/// <summary>
/// SingletonMonobehaviour class.
/// </summary>
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour
{
    /// <summary>
    /// Cache a reference to the existing instance to prevent duplicate instances.
    /// </summary>
    private static SingletonMonoBehaviour<T> instance;

    /// <summary>
    /// Initialize script state.
    /// </summary>
    internal virtual void Awake()
    {
        if (instance == null)
        {
            instance = this;
            if (this.GetType().IsDefined(typeof(GlobalDependencyAttribute), false))
            {
                DontDestroyOnLoad(this.gameObject);
            }
        }
        else
        {
            Destroy(this.gameObject);
        }
    }
}

This is simply a generic type that wraps MonoBehaviour and implements some of the logic of a singleton, allowing any class that derives from it to enforce singularity. It leverages the GlobalDependencyAttribute we added to our classes for selecting the correct cache in the DependencyProvider to determine whether the class should not be destroyed when unloading the scene. In an earlier iteration of the DependencyProvider, this logic lived there, but I realized that was the wrong separation of concerns. The DependencyProvider only cares about serving up an instance of a dependency. It’s up to that dependency to know whether it needs to exist in the scene or for the lifetime of the application, as well as whether it is critical for only one instance to ever exist.

Bookmark the permalink.

Comments are closed