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;
}
}
}
}
using UnityEngine;
using UnityEngine.UI;
public class SingletonBase<T> : MonoBehaviour where T : SingletonBase<T>
{
protected static T mInstance = null;
public static T Instance
{
get
{
if (mInstance == null)
{
mInstance = FindObjectOfType<T>();
if (FindObjectsOfType<T>().Length > 1)
{
return mInstance;
}
if (mInstance == null)
{
var instanceName = typeof(T).Name;
var instanceObj = GameObject.Find(instanceName);
if (!instanceObj)
instanceObj = new GameObject(instanceName);
mInstance = instanceObj.AddComponent<T>();
DontDestroyOnLoad(instanceObj); //保证实例例不不会被释放
}
else
{
}
}
return mInstance;
}
}
protected virtual void OnDestroy()
{
mInstance = null;
}
}
使用方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : SingletonBase<Test>
{
public bool check;
void Start()
{
Test.instance.check = true;
}
// Update is called once per frame
void Update()
{
}
}