Skip to content

Instantly share code, notes, and snippets.

@suakig
Created May 8, 2015 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save suakig/96c3c9d943191d8f535c to your computer and use it in GitHub Desktop.
Save suakig/96c3c9d943191d8f535c to your computer and use it in GitHub Desktop.
MonoSingletonFromResources.cs
using System;
using UnityEngine;
public abstract class MonoSingletonFromResources<T> : MonoBehaviour where T : MonoSingletonFromResources<T>
{
private static readonly string RESOURCES_PATH = "Prefabs/Singletons/";
static T m_Instance = null;
public static T instance
{
get
{
if( m_Instance != null )
{
return m_Instance;
}
System.Type type = typeof(T);
T instance = GameObject.FindObjectOfType(type) as T;
if( instance == null )
{
string typeName = type.ToString();
try{
GameObject gameObject = Instantiate (Resources.Load (RESOURCES_PATH + type.Name)) as GameObject;
instance = gameObject.GetComponent<T>();
gameObject.name = type.Name;
}catch(ArgumentException e){
Debug.LogError ("Problem during the creation of " + typeName);
}
}
else
{
Initialize(instance);
}
return m_Instance;
}
}
static void Initialize(T instance)
{
if( m_Instance == null )
{
m_Instance = instance;
m_Instance.OnInitialize();
}
else if( m_Instance != instance )
{
DestroyImmediate( instance.gameObject );
}
}
static void Destroyed(T instance)
{
if( m_Instance == instance )
{
m_Instance.OnFinalize();
}
}
public virtual void OnInitialize() {}
public virtual void OnFinalize() {
//FindObjectOfTypeは負荷が多いため繰り返す場合ば解放しない
m_Instance = null;
}
void Awake()
{
Initialize( this as T );
}
void OnDestroy()
{
Destroyed( this as T );
}
void OnApplicationQuit()
{
Destroyed( this as T );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment