2017-09-27 23 views
0

我是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?

我不知道辛格爾頓總體流動..

,請給我代碼審查..

作爲一個初學者,我知道的不多。我需要你的幫助。

請給我你的想法。

回答

4

如果實例爲null,爲什麼要將GameObject添加到AddComponent?

如果你想創建的腳本實例爲null if (_instance == null)

.Create新的遊戲對象

GameObject singleton = new GameObject(); 

.Create新該腳本的實例,並附它到上面創建的GameObject。在Unity中,組件必須附加到GameObject。 AddComponent函數用於將組件附加到GameObject。

_instance = singleton.AddComponent<T>(); 

爲什麼使用FindObject功能?

如果您要創建的腳本實例爲空if (_instance == null),請檢查該場景中是否存在該腳本實例。 FindObjectOfType函數僅用於查找此類型的腳本。假設我們有一個名爲SceneLoader的腳本,我們將SceneLoader傳遞給Singleton類,它將檢查SceneLoader的實例是否已經在場景中並返回該實例。如果不存在,它將返回null

爲什麼在Unity中使用Singleton?

當您只想讓一個場景中的一種腳本類型的實例時使用它。此外,與DontDestroyOnLoad,這意味着即使加載下一個場景,此實例仍然存在。它不會像其他腳本一樣被銷燬。

,請給我代碼評審

你可以要求在codereview網站代碼的改善。如果您是Unity新手,可以在他們的網站上找到Unity項目教程,以便您輕鬆入門here

+1

你可以1:1和我聊天嗎? –

+1

我很少聊天,但創建一個。我可以留幾分鐘。 – Programmer

+1

你的聊天室標題是什麼? –

相關問題