Unity 单例类模板

SingletonMonoBehaviour.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace gslb.core.util
{
    public class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
    {
        private static object _singletonLock = new object();
        private static T _instance;

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_singletonLock)
                    {
                        T[] singletonInstances = FindObjectsOfType(typeof(T)) as T[];
                        if (singletonInstances.Length > 1)
                        {
                            if (Application.isEditor)
                                Debug.LogError("MonoSingleton<T>.Instance: Only 1 singleton instance can exist in the scene. Null will be returned.");
                            return null;
                        }

                        if (singletonInstances.Length == 0)
                        {
                            GameObject singletonInstance = new GameObject();
                            _instance = singletonInstance.AddComponent<T>();
                            singletonInstance.name = "(singleton) " + typeof(T).ToString();
                        }
                        else
                            _instance = singletonInstances[0];
                    }

                    _instance = FindObjectOfType<T>();
                }

                return _instance;
            }
        }

        protected virtual void OnEnable()
        {
            if (Instance != this)
            {
                Destroy(this);
            }
        }
    }
}

Demo.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Demo:SingletonMonoBehaviour<Demo>
{
        void Awake(){
            ...
            //调用完Instance后执行
        }
	public void fun1(){
		...
	}
}

use.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class use{
	public void usefun1(){
		Demo.Instance.fun1();
	}
}

SDK使用单例模板类

如果需要将SingletonMonoBehaviour.cs封装进SDK里面(即无法挂载在unity中),则SDK中的子类(Demo.cs)中Awake执行不是 APP 开始时执行,而是调用Demo.Instance.fun1()时,调用Instance时执行

posted @   shenlei_blog  阅读(133)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示