AutoSingletonManager

From Unify Community Wiki
Jump to: navigation, search

Author: Ilya Suzdalnitski


Why use singletons?

Singletons are a great design pattern that allow us to call manager objects from anywhere in our code. The only inconvenience is having to type in the same duplicate pattern code for every singleton class.

Fret no more fellas! :)

The AutoSingletonManager is a great class that allows for automatic creation of singleton objects by simply inheriting from it.

Usage example

    public class GameUIManager : AutoSingletonManager <GameUIManager> {
        //Initialization code (called from Awake) goes in here
        public override void InitManager() { }
    }

Class Sourcecode

public abstract class AutoSingletonManager : MonoBehaviour { }
 
public abstract class AutoSingletonManager<T> : AutoSingletonManager where T : AutoSingletonManager
{
    private static bool Compare<T>(T x, T y) where T : class
    {
        return x == y;
    }
 
    #region Singleton
 
    private static T _instance = default(T);
 
    public static T Instance
    {
        get
        {
            if (!Compare<T>(default(T), _instance)) return _instance;
 
            InitInstance(true);
            return _instance;
        }
    }
 
    #endregion
 
    public void Awake()
    {
        InitInstance(false);
    }
 
    public static void InitInstance(bool shouldInitManager)
    {
        Type thisType = typeof (T);
 
        _instance = FindObjectOfType<T>();
 
        if (Compare<T>(default(T), _instance))
        {
            _instance = new GameObject(thisType.Name).AddComponent<T>();
        }
 
        //Won't call InitManager from Awake
        if (shouldInitManager)
        {
            (_instance as AutoSingletonManager<T>).InitManager();
        }
    }
 
    public virtual void InitManager() { }
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox