Singleton Pattern

  • 48
  • 0
  • 2020-02-07

1. Singleton Pattern:確保只有1個class只有單一"物件"(實例:instance)出現在整個Game中

2. GetType()

3. 使用 static實作。

 

1. 確保只有1個class只有單一"物件"(實例:instance)出現,例如:


    private void Awake()
    {
        //make sure only one GameStatus in the scene
        int gameStatusCount = FindObjectsOfType<GameStatus>().Length;

        if (gameStatusCount > 1)
        {
            gameObject.SetActive(false);//在被Destroy前,該物件會存在一小段時間,所以先關掉。
            // Destroy 比 SetActive晚執行。
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
        }

    }

 

2. GetType() : Gets the Type of the current instance.
以下例子中GetType() return 該class "MusicPlayer"

public class MusicPlayer : MonoBehaviour
{
    
    private void Awake()
    {
        SetUpSingleton();
    }

    /// <summary>
    /// make sure only one MusicPlayer in the scene
    /// </summary>
    private void SetUpSingleton()
    {
        if (FindObjectsOfType(GetType()).Length > 1)
        {
            gameObject.SetActive(false);//在被Destroy前,該物件會存在一小段時間,所以先關掉。
            // Destroy 比 SetActive晚執行。
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
        }
    }
}

3. 使用 static實作。


public class ScenePersist : MonoBehaviour {
    static ScenePersist instance = null;
    
    void Start() {  
        if (!instance) { 
            instance = this;
            DontDestroyOnLoad(gameObject);
        } else if (instance != this) {
            Destroy(gameObject);
        }
    }
}