【发布时间】:2017-09-27 18:31:04
【问题描述】:
我是 Unity 的初学者。
我在学习时遇到了一个问题。
我参考下面的文件。
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T Instance
{
get
{
if (applicationIsQuitting) {
Debug.LogWarning("[Singleton] Instance '"+ typeof(T) +
"' already destroyed on application quit." +
" Won't create again - returning null.");
return null;
}
lock(_lock)
{
if (_instance == null)
{
_instance = (T) FindObjectOfType(typeof(T));
if ( FindObjectsOfType(typeof(T)).Length > 1 )
{
Debug.LogError("[Singleton] Something went really wrong " +
" - there should never be more than 1 singleton!" +
" Reopening the scene might fix it.");
return _instance;
}
if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(singleton) "+ typeof(T).ToString();
DontDestroyOnLoad(singleton);
Debug.Log("[Singleton] An instance of " + typeof(T) +
" is needed in the scene, so '" + singleton +
"' was created with DontDestroyOnLoad.");
} else {
Debug.Log("[Singleton] Using instance already created: " +
_instance.gameObject.name);
}
}
return _instance;
}
}
}
private static bool applicationIsQuitting = false;
public void OnDestroy () {
applicationIsQuitting = true;
}
}
如果实例为空,为什么要将 GameObject 添加到 AddComponent 中?
为什么要使用 FindObject 函数?
为什么在 Unity 中使用 Singleton?
我不知道单例整体流程..
请给我代码审查..
作为初学者,我知道的不多。我需要你的帮助。
请给我你的想法。
【问题讨论】:
标签: c# generics unity3d singleton