UnityCommunity / UnitySingleton

The best way to implement singleton pattern in Unity.
https://en.wikipedia.org/wiki/Singleton_pattern
MIT License
446 stars 59 forks source link

Great job, could even be extended to support editor mode #2

Closed aybe closed 9 months ago

aybe commented 5 years ago

Thanks for the code, I believe it could be further enhanced to support editor mode, like the following:

using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using UnityEngine;

namespace Z
{
    [PublicAPI]
    [ExecuteAlways]
    public abstract class Singleton<T> : MonoBehaviour where T : Component
    {
        private static T _instance;

        public static T Instance
        {
            get
            {
                if (_instance != null)
                    return _instance;

                _instance = FindObjectOfType<T>();

                if (_instance != null)
                    return _instance;

                var o = new GameObject($"{typeof(T).Name} (Singleton)");

                _instance = o.AddComponent<T>();

                return _instance;
            }
        }

        [SuppressMessage("ReSharper", "VirtualMemberNeverOverridden.Global")]
        protected virtual void Awake()
        {
            if (_instance == null)
            {
                _instance = this as T;

                if (Application.isPlaying)
                {
                    DontDestroyOnLoad(gameObject);
                }
            }
            else
            {
                if (Application.isPlaying)
                {
                    Destroy(gameObject);
                }
                else
                {
                    DestroyImmediate(gameObject);
                }
            }
        }
    }
}

Not PR-ing, just a suggestion :)

hasanbayatme commented 9 months ago

Thank you, that's a good idea, I'll add this coupled with #4 as a patch, let me know if you have any other ideas!

hasanbayatme commented 9 months ago

Thank you, that's a good idea, I'll add this coupled with #4 as a patch, let me know if you have any other ideas!

hasanbayatme commented 9 months ago

Added basic editor mode support on e902a9f