You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.7 KiB
56 lines
1.7 KiB
using System.Collections; |
|
using System.Collections.Generic; |
|
using UnityEngine; |
|
|
|
public class PromptWinSingleton<T> : MonoBehaviour where T : PromptWinSingleton<T> |
|
{ |
|
private static T instance = null; |
|
//静态锁 |
|
private static object _lock = new object(); |
|
|
|
public static T Instance |
|
{ |
|
//获取对象 |
|
get |
|
{ |
|
//加锁 |
|
lock (_lock) |
|
{ |
|
if (instance == null) |
|
{ |
|
instance = (T)FindObjectOfType(typeof(T)); |
|
|
|
if (FindObjectsOfType(typeof(T)).Length > 1) |
|
{ |
|
Debug.LogError("[Singleton] 发生异常 " + |
|
" - 单例类只能有1个" + |
|
" 修复错误"); |
|
return instance; |
|
} |
|
|
|
if (instance == null) |
|
{ |
|
GameObject singleton = new GameObject(); |
|
instance = singleton.AddComponent<T>(); |
|
singleton.name = typeof(T).ToString() + "_singleton"; |
|
|
|
DontDestroyOnLoad(singleton); |
|
|
|
Debug.Log("[Singleton] " + typeof(T) + |
|
" 单例创建成功 " + instance.gameObject.name); |
|
} |
|
else |
|
{ |
|
//Debug.Log("[Singleton] 已经创建: " + |
|
// instance.gameObject.name); |
|
} |
|
} |
|
|
|
//返回单例字段 |
|
return instance; |
|
} |
|
} |
|
} |
|
|
|
void OnApplicationQuit() { if (instance != null) instance = null; } |
|
}
|
|
|