当先锋百科网

首页 1 2 3 4 5 6 7

1.静态类单例:用于数据类型存储

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class Singleton<T> where T : class, new()
{
    private static T instance = null;

    private static readonly object locker = new object();
    public static T Instance
    {
        get
        {
            lock (locker)
            {
                if (instance == null)
                    instance = new T();
                return instance;
            }
        }
    }
}

2.继承 MonoBehaviour的单例:常用于跟场景对象交互

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T s_Instance;

    public static T Instance
    {
        get
        {
            if (s_Instance == null)
            {
                lock (typeof(T))
                {
                    if (s_Instance == null)
                    {
                        s_Instance = FindObjectOfType<T>();
                        if (s_Instance == null)
                        {
                            var go = new GameObject(typeof(T).Name);
                            s_Instance = go.AddComponent<T>();
                        }
                    }
                }
            }
            return s_Instance;
        }
    }

    public static void DestroyInstance()
    {
        DestroyImmediate(s_Instance);
        s_Instance = null;
    }
}