Last active
January 7, 2021 07:46
-
-
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.
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; | |
/** | |
* 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