Unity 单例-接口模式

单例-接口模式


使用接口方式实现的单例可以继承其它类,更加方便

Unity 单例-接口模式_第1张图片

using System.Collections;
using System.Collections.Generic;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
namespace ZYF
{

    public interface ISingleton<TMono> where TMono : MonoBehaviour
    {
        private static string rootName = "MonoSingletonRoot";
        private static GameObject monoSingletionRoot;
        private static bool isSpawnRootGo = false;
        static TMono _instance;
        public static TMono Instance
        {
            get {
                if (_instance == null && Application.isPlaying)
                {
                    _instance = GameObject.FindObjectOfType<TMono>();
                    if (_instance == null)
                    {
                        if (monoSingletionRoot == null)
                        {
                            monoSingletionRoot = GameObject.Find(rootName);
                            if (monoSingletionRoot == null && isSpawnRootGo ==false) {
                                isSpawnRootGo=true;
                                monoSingletionRoot = new GameObject(rootName);
                                monoSingletionRoot.OnDestroyAsObservable().Subscribe(_ => {
                                    isSpawnRootGo = false;
                                }).AddTo(monoSingletionRoot);
                            }
                        }
                        if (monoSingletionRoot != null)
                        {
                            _instance = monoSingletionRoot.GetComponent<TMono>();
                        }
                        if (_instance == null)
                        {
                            if (monoSingletionRoot != null)
                            {
                                _instance = monoSingletionRoot.AddComponent<TMono>();
                            }
                            else
                            {
                                Debug.Log(rootName + "null!!!");
                            }
                        }
                    }
                }
                if (_instance == null)
                {
                    Debug.Log(typeof(TMono).Name + "Null");
                }
                return _instance;
            }
        }
    }
}

你可能感兴趣的:(Unity,unity,单例,接口)