Unity SingletonMono

本文探讨了 Unity 游戏引擎中 Singleton 模式的实现,以及在 Awake 函数中不当使用 GetInstance 的潜在问题。警告了将所有重要变量集中于 Singleton 中的风险,并指出在多线程环境中 Singleton 的局限性。建议谨慎使用 Singleton,特别是在单元测试和多线程场景下。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using UnityEngine;

public abstract class SingletonMono<T> : MonoBehaviour where T : Component
{
    private static T m_instance;

    private static bool m_isAppQuitting = false;

    public static T GetInstance()
    {
        if (m_isAppQuitting)
        {
        	return null;
        }
        if (m_instance == null)
        {
            m_instance = FindObjectOfType<T>();
            if (m_instance == null)
            {
                GameObject obj = new GameObject();
                obj.name = typeof(T).Name;
                m_instance = obj.AddComponent<T>();
            }
        }
        return m_instance;
    }

    protected virtual void Awake()
    {
        if (m_instance == null)
        {
            m_instance = this as T;
            DontDestroyOnLoad(gameObject);
        }
        else if (m_instance != this as T)
        {
            Destroy(gameObject);
        }
        else
        {
        	DontDestroyOnLoad(gameObject);
        }
    }

    private void OnApplicationQuit()
    {
        m_isAppQuitting = true;
    }
}
IMPROPER USAGE
  1. Don’t call GetInstance from another objects Awake function
  2. Don’t use 1 singleton to access every important variable in your game
  3. Don’t use singletons just to access data or references if they are not part of the design
MAIN AREAS THEY WON’T WORK
  1. Unit Tests because they require copies/mock objects to test
  2. Multithreading
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值