找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
游戏黄埔已经开课啦,大家速速报名赶快上车
查看: 85|回复: 0

完整的继承MonoBehavior的单例写法:

[复制链接]

185

主题

32

回帖

1056

积分

管理员

积分
1056
发表于 2025-9-24 02:06:28 | 显示全部楼层 |阅读模式
  1. public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
  2. {
  3.     private static T m_instance;
  4.     private static readonly object m_lock = new object();
  5.     private static bool m_applicationIsQuitting = false;

  6.     public static T Instance
  7.     {
  8.         get
  9.         {
  10.             if (m_applicationIsQuitting)
  11.                 return null;

  12.             lock (m_lock)
  13.             {
  14.                 if (m_instance == null)
  15.                 {
  16.                     m_instance = FindObjectOfType<T>();
  17.                     if (m_instance == null)
  18.                     {
  19.                         GameObject go = new GameObject($"{typeof(T).Name} (Singleton)");
  20.                         m_instance = go.AddComponent<T>();
  21.                         DontDestroyOnLoad(go); // 如果需要跨场景
  22.                     }
  23.                 }
  24.                 return m_instance;
  25.             }
  26.         }
  27.     }

  28.     protected virtual void Awake()
  29.     {
  30.         if (m_instance == null)
  31.         {
  32.             m_instance = this as T;
  33.             DontDestroyOnLoad(gameObject);
  34.         }
  35.         else if (m_instance != this)
  36.         {
  37.             Destroy(gameObject);
  38.         }
  39.     }

  40.     protected virtual void OnApplicationQuit()
  41.     {
  42.         m_applicationIsQuitting = true;
  43.     }
  44. }
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|平顶山市图灵科技 ( 豫ICP备2024088136号-1| 豫公网安备41040202000275号 )

GMT+8, 2025-10-30 05:33 , Processed in 0.042283 second(s), 20 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表