ruk·si

⬜️ Unity
Toolbox

Updated at 2016-10-30 11:00

Toolbox is a simple singleton pattern where you have one persistent game object including all script tools you need.

using UnityEngine;

namespace MyCompany
{
    public class Toolbox : Singleton<Toolbox>
    {
        protected Toolbox() {}

        public static bool ApplicationIsQuitting
        {
            get { return applicationIsQuitting; }
        }

        public static T Get<T> () where T: Component
        {
            return Instance.GetOrAddComponent<T>();
        }
    }
}
using UnityEngine;

namespace MyCompany
{
    // for creating singleton scripts like e.g. Toolbox.
    public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
    {
        protected static bool applicationIsQuitting = false;
        private static object createLock = new object();
        private static T instance;
        public static T Instance
        {
            get
            {
                if (applicationIsQuitting) {
                    return null;
                }
                lock(createLock) {
                    if (instance == null) {
                        instance = (T) FindObjectOfType(typeof(T));
                        if (instance == null) {
                            var singleton = new GameObject();
                            instance = singleton.AddComponent<T>();
                            singleton.name = typeof(T).ToString();
                            DontDestroyOnLoad(singleton);
                        } else if (FindObjectsOfType(typeof(T)).Length > 1) {
                            Debug.LogWarning("more than 1 singleton!", instance);
                            return instance;
                        }
                    }
                    return instance;
                }

            }
        }
        private void OnDestroy () {
            applicationIsQuitting = true;
        }
    }
}
using UnityEngine;

namespace MyCompany
{
    public static class TransformExtensions
    {
        public static T GetOrAddComponent<T>(this Component child) where T: Component
        {
            T result = child.GetComponent<T>();
            if (result == null) { result = child.gameObject.AddComponent<T>(); }
            return result;
        }
    }
}

Call stack on initialization:

Toolbox.Get<MyScript>().DoStuff();
// 1. Get<T>()
// 2. Awake()
// 3. OnEnable() // But only if enabled.
// 4. DoStuff()
// 5. Start()    // But only if enabled.