Forked from mstevenson/MonoBehaviourSingleton.cs
Last active
August 29, 2015 14:16
-
-
Save birdinforest/d4c719cc7140f4734597 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 UnityEngine; | |
using System.Collections; | |
public class MonoBehaviourSingleton<T> : MonoBehaviour | |
where T : Component | |
{ | |
private static T _instance; | |
public static T Instance { | |
get { | |
if (_instance == null) { | |
var objs = FindObjectsOfType (typeof(T)) as T[]; | |
if (objs.Length > 0) | |
_instance = objs[0]; | |
if (objs.Length > 1) { | |
Debug.LogError ("There is more than one " + typeof(T).Name + " in the scene."); | |
} | |
if (_instance == null) { | |
GameObject obj = new GameObject (); | |
obj.hideFlags = HideFlags.HideAndDontSave; | |
_instance = obj.AddComponent<T> (); | |
} | |
} | |
return _instance; | |
} | |
} | |
} | |
public class MonoBehaviourSingletonPersistent<T> : MonoBehaviour | |
where T : Component | |
{ | |
public static T Instance { get; private set; } | |
public virtual void Awake () | |
{ | |
if (Instance == null) { | |
Instance = this as T; | |
DontDestroyOnLoad (this); | |
} else { | |
Destroy (gameObject); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment