Skip to content

Instantly share code, notes, and snippets.

@simonbroggi
Last active January 7, 2021 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonbroggi/720ea3388ae10ead6771 to your computer and use it in GitHub Desktop.
Save simonbroggi/720ea3388ae10ead6771 to your computer and use it in GitHub Desktop.
unity singleton that can be used from editor scripts as well as in game.
using UnityEngine;
using System.Collections;
/**
* Singleton usefull if fields set in editor scripts need to be used in game.
*/
public class ResourcesSingleton : MonoBehaviour {
private static ResourcesSingleton _instance;
public static ResourcesSingleton instance {
get {
if(_instance == null) {
#if UNITY_EDITOR
GameObject o;
if(Application.isPlaying){
o = (GameObject)Instantiate(Resources.Load("ResourcesSingleton"));
}
else{
o = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Resources/ResourcesSingleton.prefab");
if(o == null){
GameObject tempGO = new GameObject("ResourcesSingleton", typeof(ResourcesSingleton) );
o = UnityEditor.PrefabUtility.CreatePrefab("Assets/Resources/ResourcesSingleton.prefab", tempGO);
DestroyImmediate(tempGO);
}
}
#else
GameObject o = (GameObject)Instantiate(Resources.Load("ResourcesSingleton"));
#endif
_instance = ((GameObject)o).GetComponent<ResourcesSingleton>();
}
return _instance;
}
}
void Awake () {
if(_instance == null){
_instance = this;
DontDestroyOnLoad(gameObject);
}
else if(_instance != this){
Debug.LogWarning(_instance.name + " already exists! Destroying " +this.name);
Destroy(gameObject);
}
}
void OnDestroy () {
if(_instance == this){
_instance = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment