Last active
August 29, 2015 14:21
-
-
Save grimmdev/0c6c2f1ec81ca74abeca to your computer and use it in GitHub Desktop.
MonoBehaviourUtility for shared instances. The beauty of Singletons.
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; | |
public class ExampleManager : MonoBehaviour | |
{ | |
static public ExampleManager sharedManager | |
{ | |
get | |
{ | |
return MonoBehaviourUtility.GetManager<ExampleManager>( ref _sharedManager ); | |
} | |
} | |
static private ExampleManager _sharedManager; | |
} |
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.Collections.Generic; | |
using System.IO; | |
static public class MonoBehaviourUtility | |
{ | |
static public T GetManager<T>( ref T manager ) where T : MonoBehaviour | |
{ | |
if (manager == null) | |
{ | |
manager = (T)GameObject.FindObjectOfType( typeof( T ) ); | |
if (manager == null) | |
{ | |
GameObject gameObject = new GameObject( typeof( T ).ToString() ); | |
manager = (T)gameObject.AddComponent( typeof( T ) ); | |
} | |
} | |
return manager; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment