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时执行
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律