Last active
March 9, 2020 21:49
-
-
Save ogxd/6f54ce5742de2b8a470d377b73e73fd0 to your computer and use it in GitHub Desktop.
Easy project references for Unity, without using Resources.Load ! Faster and cleaner.
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; | |
public class ProjectReferences<T> : ScriptableObject where T : ScriptableObject | |
{ | |
private static T instance; | |
public static T Instance { | |
get { | |
if (instance == null) { | |
instance = Resources.Load<T>(typeof(T).Name); | |
if (instance == null) { | |
instance = CreateInstance<T>(); | |
#if UNITY_EDITOR | |
UnityEditor.AssetDatabase.CreateAsset(instance, $"Assets/Resources/{typeof(T).Name}.asset"); | |
#else | |
Debug.LogError($"There is no '{typeof(T).Name}' in your resources. Access {typeof(T).Name} class in the Editor to initialize it."); | |
#endif | |
} | |
} | |
return instance; | |
} | |
} | |
} | |
//---- EXAMPLE : ---- | |
// Just create a class that inherits from ProjectReferences<YourClass> ! | |
// You can have an unlimited number of those ! | |
public class ProjectIcons : ProjectReferences<ProjectIcons> | |
{ | |
[SerializeField] | |
private Texture2D folder; | |
public static Texture2D Folder => Instance.folder; | |
[SerializeField] | |
private Texture2D cursor; | |
public static Texture2D Cursor => Instance.folder; | |
// Anything else pretty much ! | |
// Materials, Prefabs, Images, Soundclips... | |
} | |
// Then, in anywhere in you code, you can use ProjectIcons.Folder ! | |
// It's faster and safer than Resources.Load. | |
// Also, as the ProjectIcons instance is already in resources, its references don't require to be in the resource folder. | |
// This way, things are well organized ! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment