Last active
January 23, 2017 09:12
-
-
Save umiyuki/e984b19e1623c61f9ea3c764bab42c1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using System; | |
public class SingletonInstances : SingletonMonoBehaviour<SingletonInstances> { | |
[SerializeField] List<MonoBehaviour> instances; | |
public MonoBehaviour GetSingletonInstance(Type t) | |
{ | |
for (int i = 0; i < instances.Count; i++) | |
{ | |
if (instances[i].GetType() == t) | |
{ | |
return instances[i]; | |
} | |
} | |
return null; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
//シングルトン(MonoBehaviour)を作れるクラス | |
//継承して使う | |
//インスタンスがダブッたら自滅する機能も入ってます。 | |
//インスタンスが複数 | |
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T> | |
{ | |
public bool _DontDestroyOnLoad = true; | |
//インスタンス | |
protected static T instance; | |
public static T Instance | |
{ | |
get | |
{ | |
//awakeで呼ばれたら無い | |
if (instance == null) | |
{ | |
instance = (T)FindObjectOfType(typeof(T)); | |
if (instance == null) | |
{ | |
instance = (T)SingletonInstances.Instance.GetSingletonInstance(typeof(T)); | |
if (instance == null) | |
{ | |
Debug.LogWarning(typeof(T) + "is nothing"); | |
} | |
} | |
} | |
return instance; | |
} | |
} | |
//Awakeでインスタンス作成 | |
protected virtual void Awake() | |
{ | |
CheckInstance(); | |
//DontDestroyOnLoad機能 | |
if (_DontDestroyOnLoad) | |
{ | |
DontDestroyOnLoad(this); | |
} | |
} | |
//インスタンスがあるかどうか確認 | |
protected bool CheckInstance() | |
{ | |
//インスタンスがなければ | |
if (instance == null) | |
{ | |
instance = (T)this; | |
return true; | |
} | |
//インスタンスが自分なら正常 | |
else if (Instance == this) | |
{ | |
return true; | |
} | |
//インスタンスがあって自分じゃないケースはシングルトンとして異常なのでデストロイする | |
//Destroy(this); | |
Destroy(gameObject); //ゲームオブジェクト削除 | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment