Unity Engine #3 デザインパターン
この記事では、各種コードのデザインパターンを紹介します。GoFの『デザインパターン:オブジェクト指向における再利用のための設計』では、合計23種類のデザインパターンが紹介されています。Unityで広く大量に使われているパターンとして、このノートではシングルトンパターン、オブザーバーパターン、ファクトリーパターンを主に説明します。
シングルトンパターン Singleton Pattern
シングルトンパターンとは、クラスがシーンに1つのインスタンスしかない場合に、グローバルなアクセスポイントを提供することです。よくある用途は各種Managerです。
Plain Textpublic class GameManager : MonoBehaviour
{
private static GameManager _instance;
public static GameManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<GameManager>();
if (_instance == null)
{
_instance = new GameObject("Spawned GameManager", typeof(GameManager)).GetComponent<GameManager>();
}
}
return _instance;
}
}
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
else
{
_instance = this;
DontDestroyOnLoad(this.gameObject);
}
}
}
その後、他のC#スクリプトでGameManager.Instance.SomeFunction()でGameManagerのpublic関数と変数を呼び出せます。
