Unity3d 中的单例模式

U3D中许多地方需要用到单例,然后就是如下的情况:

private static SoundManager _instance;
public static SoundManager GetInstance
{
    return _instance;
}

void Awake()
{
    _instance = this;
}

假如以上的代码没有任何问题,但是每个单例都要加上这么一段代码也是挺烦的,所有可以加上泛型。

using UnityEngine;

public abstract class Singleton<T> :MonoBehaviour
    where T:MonoBehaviour
{
    private static T _instance = null;

    public static T Instance
    {
        get { return _instance; }
    }

    protected virtual void Awake()
    {
        _instance = this as T;
    }
}

当然更好的是下面这一种。

using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;
    private static object _lock = new object();
    private static bool applicationIsQuitting = false;

    public static T GetInstance
    {
        get
        {
            if (applicationIsQuitting)
            {
                return null;
            }
            lock (_lock)    // 可以确保代码完整运行 不会被线程打断
            {
                if (null == _instance)
                {
                    _instance = (T) FindObjectOfType(typeof (T));

                    if (FindObjectOfType(typeof (T)).Length > 1)
                    {
                        return _instance;
                    }

                    if (null == _instance)
                    {
                        GameObject singleton = new GameObject();
                        _instance = singleton.AddComponent<T>();
                        singleton.name = "(singleton)" + typeof (T).ToString();
                        DontDestroyOnLoad(singleton);
                    }
                }
                return _instance;
            }
        }
    }

    public void OnDestroy()
    {
        applicationIsQuitting = true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值