Created
June 7, 2019 15:18
-
-
Save rtlsilva/4ac2cb2725e9a93954c6ef6580a08df2 to your computer and use it in GitHub Desktop.
Store a path to a resource instead of referencing the object
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; | |
public class ResourcePathAttribute : PropertyAttribute { | |
public Type resourceType; | |
public ResourcePathAttribute(Type t) { | |
this.resourceType = t; | |
} | |
} |
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 System; | |
using UnityEngine; | |
using UnityEditor; | |
[CustomPropertyDrawer(typeof(ResourcePathAttribute))] | |
public class ResourcePathPropertyDrawer : PropertyDrawer { | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { | |
if (property.propertyType == SerializedPropertyType.String) { | |
Type objType = ((ResourcePathAttribute)attribute).resourceType; | |
UnityEngine.Object obj = null; | |
if (property.stringValue != "") { | |
obj = Resources.Load(property.stringValue, objType); | |
} | |
obj = EditorGUI.ObjectField(position, label, obj, objType, false); | |
string assetPath = AssetDatabase.GetAssetPath(obj); | |
if (assetPath != "") { | |
string[] split = assetPath.Split(new string[]{ "Resources/" }, StringSplitOptions.RemoveEmptyEntries); | |
string ext = System.IO.Path.GetExtension(assetPath); | |
property.stringValue = split[split.Length - 1].Replace(ext, ""); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment