シングルトンクラスを使う

シングルトンクラスSingletonMonoBehaviourを作成する

大元となるシングルトンクラスはこちらを1つだけ作成しておいて継承して使用します。

using UnityEngine;
using System.Collections;
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T>
{
	protected static T instance;
	public static T Instance
	{
		get
		{
			if (instance == null)
			{
				instance = (T)FindObjectOfType (typeof(T));
				if (instance == null)
				{
					Debug.LogWarning (typeof(T) + "is nothing");
				}
			}
			return instance;
		}
	}
	protected void Awake()
	{
		CheckInstance();
	}
	protected bool CheckInstance()
	{
		if (instance == null)
		{
			instance = (T)this;
			return true;
		}
		else if(Instance == this)
		{
			return true;
		}

		Destroy(this);
		return false;
	}
}

SingletonMonoBehaviourを継承した実際に使用するクラスを作成する

例えばGlobalDataというアプリ内で使う共通の変数を入れておく入れ物を作成する場合にはこのように記載します。

using System.Collections;
using System.Collections.Generic;
public class GlobalData : SingletonMonoBehaviour<GlobalData>
{
  public void Method()
	{
		~
	}
}

GlobalData.Instance.Method()みたいな感じで使います。