我是Unity的初學者。如何在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;
}
}
如果實例爲null,爲什麼GameObject要添加到AddComponent?
爲什麼使用FindObject函數?
爲什麼在Unity中使用Singleton?
我不知道辛格爾頓總體流動..
,請給我代碼審查..
作爲一個初學者,我知道的不多。我需要你的幫助。
請給我你的想法。
你可以1:1和我聊天嗎? –
我很少聊天,但創建一個。我可以留幾分鐘。 – Programmer
你的聊天室標題是什麼? –