Last active
October 23, 2018 12:06
-
-
Save nagedev/d92733b33e9ab5a623afb04694b9ccf7 to your computer and use it in GitHub Desktop.
SingletonScriptable
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 System.Linq; | |
using UnityEditor; | |
using UnityEngine; | |
public abstract class SingletonScriptable<T> : ScriptableObject where T : ScriptableObject | |
{ | |
static T _instance = null; | |
public static T instance | |
{ | |
get | |
{ | |
if (!_instance) | |
{ | |
_instance = Resources.FindObjectsOfTypeAll<T>().FirstOrDefault(); | |
if (!_instance) | |
{ | |
string resourceName = typeof(T).ToString(); | |
AssetDatabase.CreateAsset(CreateInstance<T>(), $"Assets/Resources/{resourceName}.asset"); | |
_instance = Resources.FindObjectsOfTypeAll<T>().FirstOrDefault(); | |
} | |
} | |
return _instance; | |
} | |
} | |
} |
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 System.Linq; | |
using UnityEditor; | |
using UnityEngine; | |
public abstract class SingletonScriptable<T> : ScriptableObject where T : ScriptableObject | |
{ | |
private static T _instance = null; | |
public static T instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
{ | |
//find instance in resources | |
_instance = Resources.FindObjectsOfTypeAll<T>().FirstOrDefault(); | |
//if there is no instance of this singleton, create it | |
if (_instance == null) | |
{ | |
if (Application.isEditor) //not using predefines allows us to put this code into dll | |
{ | |
//get name for asset (type name without namespaces) | |
string resourceName = typeof(T).ToString(); | |
string[] splitted = resourceName.Split('.'); | |
resourceName = splitted.Last(); | |
//create instance | |
_instance = CreateInstance<T>(); | |
//save to Resources folder | |
AssetDatabase.CreateAsset(_instance, $"Assets/Resources/{resourceName}.asset"); | |
} | |
else | |
{ | |
//create instance | |
_instance = CreateInstance<T>(); | |
} | |
} | |
} | |
return _instance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment