Skip to content

Instantly share code, notes, and snippets.

@rtlsilva
Created June 7, 2019 15:18
Show Gist options
  • Save rtlsilva/4ac2cb2725e9a93954c6ef6580a08df2 to your computer and use it in GitHub Desktop.
Save rtlsilva/4ac2cb2725e9a93954c6ef6580a08df2 to your computer and use it in GitHub Desktop.
Store a path to a resource instead of referencing the object
using UnityEngine;
using System;
public class ResourcePathAttribute : PropertyAttribute {
public Type resourceType;
public ResourcePathAttribute(Type t) {
this.resourceType = t;
}
}
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