Unity3D 单例模式

简洁

在游戏开发中会经常使用到单例模式,什么时候会用到单例模式呢?有一些数据会在整个游戏(程序)生命中一直持续到游戏结束的数据。例如:玩家数据

代码

提供两种单例:

  1. C#中的单例。
  2. Unity3D继承MonoBehaviour的单例。
using UnityEngine;

namespace Singleton
{
    public abstract class Singleton<T> where T : new()
    {
        static object _lock = new object();
        private static T _instance;

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }

        public virtual void Release()
        {
            _instance = default(T);
        }
    }

    public class SingletonMono<T> : MonoBehaviour where T : Component
    {
        private static bool _isApplicationQuit = false;
        private static T _instance;

        public bool IsLive
        {
            get
            {
                if (_instance == null)
                {
                    return false;
                }
                return !_isApplicationQuit;
            }
        }

        public static T Instance
        {
            get
            {
                if (_instance == null && !_isApplicationQuit)
                {
                    _instance = FindObjectOfType(typeof(T)) as T;
                    if (_instance == null)
                    {
                        GameObject obj = new GameObject();
                        obj.name = typeof(T).Name.ToString();
                        _instance = (T)obj.AddComponent(typeof(T));
                    }
                    if (Application.isPlaying)
                    {
                        GameObject.DontDestroyOnLoad(_instance);
                    }
                }
                return _instance;
            }
        }

        protected virtual void OnApplicationQuit()
        {
            _isApplicationQuit = true;
        }

        protected virtual void OnDestory()
        {
            _isApplicationQuit = true;
            _instance = null;
        }
    }
}

你可能感兴趣的:(游戏开发,c#)