Unity | 工具类-单例

using UnityEngine;

public abstract class MonoSinglton<T> : MonoBehaviour
    where T : MonoBehaviour
{
    private static T _instance;

    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<T>();

                if (_instance == null)
                {
                    var obj = new GameObject($"@{typeof(T).Name}");
                    _instance = obj.AddComponent<T>();
                }
            }

            return _instance;
        }
        set { _instance = value; }
    }
}

使用:

public class RaceAudioManager : MonoSinglton<RaceAudioManager>
{
    //...
}

猜你喜欢

转载自blog.csdn.net/weixin_39766005/article/details/137072169