您当前的位置: 首页 >  unity

CoderZ1010

暂无认证

  • 3浏览

    0关注

    168博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Unity 对单例的封装

CoderZ1010 发布时间:2020-10-13 19:55:38 ,浏览量:3

using System;
using UnityEngine;
using System.Reflection;

[AttributeUsage(AttributeTargets.Class)]
public class SingletonAttribute : Attribute
{
    public bool DontDestroyOnLoad { get; }
    public SingletonAttribute(bool dontDestroyOnLoad)
    {
        DontDestroyOnLoad = dontDestroyOnLoad;
    }
}

public abstract class Singleton : MonoBehaviour where T : Singleton
{
    protected static T mInstance;
    public static T Instance
    {
        get
        {
            if(null == mInstance)
            {
                mInstance = CreateSingleton();
            }            
            return mInstance;
        }
    }
    public static T CreateSingleton() where T : Singleton
    {
        T retInstance = FindObjectOfType();
        if (null == retInstance)
        {
            retInstance = new GameObject(typeof(T).Name.ToString()).AddComponent();           
        }
        MemberInfo mi = typeof(T);
        var attributes = mi.GetCustomAttributes(true);
        foreach (var attribute in attributes)
        {
            if (attribute is SingletonAttribute attr)
            {
                if (attr.DontDestroyOnLoad)
                {
                    DontDestroyOnLoad(retInstance);
                }
            }
        }
        return retInstance;
    }
}

需要作为单例的类,只需继承Singleton

使用[Singleton(true)]属性 表示该单例物体在加载场景时做不销毁处理。

例如下例中的Foo类,继承Singleton后,即可在其他类中进行调用 Foo.Instance.TestMethod()

[Singleton(true)]
public class Foo : Singleton
{
    public void TestMethod()
    {
        Debug.Log("Test");
    }
}

关注
打赏
1653184800
查看更多评论
立即登录/注册

微信扫码登录

0.1870s