# 写在前面
单例模式在 Unity 中是一种非常常用的方式,和传统单例不同,在 Unity 中针对不同的情况可分为以下几种方式❤️ 。
![87590528_p0]()
# 普通单例
| namespace singleton |
| { |
| |
| |
| |
| |
| public abstract class Singleton<T> where T : new() |
| { |
| private static T _instance; |
| |
| public static T Instance |
| { |
| get |
| { |
| if (_instance!=null) |
| { |
| return _instance; |
| } |
| _instance=new T(); |
| return _instance; |
| } |
| } |
| } |
| } |
# 单例管理器
| using UnityEngine; |
| |
| namespace singleton |
| { |
| |
| |
| |
| |
| public abstract class SingletonManager<T> : MonoBehaviour where T : MonoBehaviour |
| { |
| private static T _instance; |
| public static T Instance |
| { |
| get |
| { |
| |
| if (_instance != null) return _instance; |
| |
| var go= GameObject.Find(typeof(T) + "").GetComponent<T>(); |
| if (go!=null) |
| { |
| _instance = go; |
| return _instance; |
| } |
| var ins = new GameObject(typeof(T)+""); |
| _instance = ins.AddComponent<T>(); |
| Debug.Log($"创建 {typeof(T)} "); |
| return _instance; |
| |
| } |
| private set { } |
| } |
| |
| protected virtual void Awake() |
| { |
| |
| DontDestroyOnLoad(gameObject); |
| } |
| } |
| } |
# 单例 ScriptableObject
- 适用于 ScriptableObject 单例数据存储
- 需要放置在 Resource 目录下用于读取
| using System.Linq; |
| using UnityEngine; |
| |
| namespace singleton |
| { |
| |
| |
| |
| |
| public abstract class SingletonSoManager<T> : ScriptableObject where T : Object |
| { |
| private static T _instance; |
| |
| public static T Instance |
| { |
| get |
| { |
| if (_instance!=null) |
| { |
| return _instance; |
| } |
| |
| var ins= Resources.FindObjectsOfTypeAll<T>().FirstOrDefault(); |
| if (!ins) |
| { |
| Debug.LogError(nameof(T)+" 不存在!!"); |
| return null; |
| } |
| |
| _instance = ins; |
| return _instance; |
| } |
| |
| } |
| } |
| } |