77 lines
2.2 KiB
C#
77 lines
2.2 KiB
C#
|
using System;
|
|||
|
using System.Collections;
|
|||
|
using System.Collections.Generic;
|
|||
|
using UnityEngine;
|
|||
|
|
|||
|
public class Singel : MonoBehaviour
|
|||
|
{
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
public class BaseSingleton<T> where T : new()
|
|||
|
{
|
|||
|
private static T instance;
|
|||
|
//保护构造函数,保证单例只能在内部创建
|
|||
|
protected BaseSingleton() { }
|
|||
|
public static T Instance
|
|||
|
{
|
|||
|
get
|
|||
|
{
|
|||
|
if (instance == null)
|
|||
|
{
|
|||
|
instance = new T();
|
|||
|
}
|
|||
|
return instance;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
|
|||
|
{
|
|||
|
private static T instance;
|
|||
|
private readonly static object obj = new object();
|
|||
|
public static T Instance
|
|||
|
{
|
|||
|
get
|
|||
|
{
|
|||
|
if (instance != null) { return instance; }
|
|||
|
lock (obj)
|
|||
|
{
|
|||
|
Type type = typeof(T);
|
|||
|
|
|||
|
// 改用 Resources.FindObjectsOfTypeAll 来查找所有的实例(包括禁用的对象)
|
|||
|
T[] instances = Resources.FindObjectsOfTypeAll<T>();
|
|||
|
// 如果场景中存在多个实例,抛出异常
|
|||
|
if (instances.Length > 1)
|
|||
|
{
|
|||
|
Debug.Log(new Exception(string.Format("Singleton类型{0}存在多个实例", type.Name)));
|
|||
|
instance = instances[0]; // 默认选择第一个实例
|
|||
|
return instance;
|
|||
|
}
|
|||
|
|
|||
|
// 如果场景中找到了唯一的实例,直接返回
|
|||
|
if (instances.Length == 1)
|
|||
|
{
|
|||
|
instance = instances[0];
|
|||
|
return instance;
|
|||
|
}
|
|||
|
|
|||
|
// 如果没有找到实例,实例化一个空物体并添加T脚本
|
|||
|
instance = new GameObject("Singleton Of " + typeof(T).Name.ToString(), typeof(T)).GetComponent<T>();
|
|||
|
Debug.LogError("创建了新的");
|
|||
|
return instance;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
virtual public void Awake()
|
|||
|
{
|
|||
|
// 如果 `instance` 已经被初始化(即通过 `Instance` 属性),销毁当前挂载的实例
|
|||
|
if (instance == null)
|
|||
|
{
|
|||
|
instance = this as T;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|