Skip to content

Instantly share code, notes, and snippets.

@yagero
Last active November 14, 2017 13:54
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yagero/e07b00785c1e98001b498a8a1b467824 to your computer and use it in GitHub Desktop.
Save yagero/e07b00785c1e98001b498a8a1b467824 to your computer and use it in GitHub Desktop.
Unity: Make your unique data accessible globally w/o having to link it, by using a 'ScriptableObjectSingleton'
using UnityEngine;
public class ScriptableObjectSingleton<T> : ScriptableObject where T : ScriptableObject
{
static T m_Instance = null;
public static T Instance
{
get
{
if (m_Instance == null)
{
var found = Resources.LoadAll<T>("");
Debug.AssertFormat(found.Length != 0,
"Can't find any resource of type '{0}'. Make sure you have one in a 'Resources' folder.",
typeof(T));
Debug.AssertFormat(found.Length <= 1,
"Could find {0} resources of type '{1}'. Make sure you have only one in your project!",
found.Length, typeof(T));
m_Instance = found[0];
}
return m_Instance;
}
}
protected virtual void OnEnable()
{
Debug.AssertFormat(m_Instance == null, "Trying to instantiate another {0}, which is forbidden.", typeof(T));
}
}
// ====================
// SAMPLES
// ====================
/*
// CLASS HOLDING YOUR GLOBAL DATA
[CreateAssetMenu]
public class GlobalData : ScriptableObjectSingleton<GlobalData>
{
[Range(0f, 1f)]
public float MyValue = 0.5f;
public Texture MyTexture = null;
}
*/
/*
// USAGE
public class Usage : MonoBehaviour
{
void OnGUI ()
{
// Usage Example
var value = GlobalData.Instance.MyValue;
var texture = GlobalData.Instance.MyTexture;
var rect = Camera.main.pixelRect;
rect.width *= value;
rect.height *= value;
GUI.DrawTexture(rect, texture);
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment