Skip to content

Instantly share code, notes, and snippets.

@umiyuki
Last active January 23, 2017 09:12
Show Gist options
  • Save umiyuki/e984b19e1623c61f9ea3c764bab42c1b to your computer and use it in GitHub Desktop.
Save umiyuki/e984b19e1623c61f9ea3c764bab42c1b to your computer and use it in GitHub Desktop.
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;
}
}
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