Skip to content

Instantly share code, notes, and snippets.

@grimmdev
Last active August 29, 2015 14:21
Show Gist options
  • Save grimmdev/0c6c2f1ec81ca74abeca to your computer and use it in GitHub Desktop.
Save grimmdev/0c6c2f1ec81ca74abeca to your computer and use it in GitHub Desktop.
MonoBehaviourUtility for shared instances. The beauty of Singletons.
using UnityEngine;
using System.Collections;
public class ExampleManager : MonoBehaviour
{
static public ExampleManager sharedManager
{
get
{
return MonoBehaviourUtility.GetManager<ExampleManager>( ref _sharedManager );
}
}
static private ExampleManager _sharedManager;
}
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