Created
September 24, 2016 04:51
-
-
Save kalineh/e85e163a87bf08e45b3ba72300757c21 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
using System.Reflection; | |
public class SingletonMonoBehaviourOnDemand<T> | |
: MonoBehaviour | |
where T : Component | |
{ | |
private static T instance; | |
public static T Instance | |
{ | |
get | |
{ | |
if (instance == null) | |
instance = Initialize(); | |
return instance; | |
} | |
} | |
public static T Initialize() | |
{ | |
var typename = typeof(T).Name; | |
var instance = GameObject.Find(typename); | |
if (instance == null) | |
instance = new GameObject(typename, typeof(T)); | |
var component = instance.GetComponent<T>(); | |
if (component == null) | |
component = instance.AddComponent<T>(); | |
var flags = | |
BindingFlags.Public | | |
BindingFlags.Instance | | |
BindingFlags.FlattenHierarchy; | |
var type = typeof(T); | |
var method = type.GetMethod("OnScriptReload", flags); | |
// can be null | |
if (method != null) | |
{ | |
method.Invoke(component, null); | |
} | |
return component; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment