Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A custom attribute to easily link prefab's paths instead of linking directly the prefab itself, especially useful inside scriptable objects and if you don't want Unity to load all the prefabs' resources as soon as the Scriptable Object loads.
using UnityEngine;
using System;
using System.Collections;
public class AssetPathAttribute : PropertyAttribute {
System.Type type;
string label;
public bool isResource;
public AssetPathAttribute(string l, System.Type t, bool isR) {
type = t;
label = l;
isResource = isR;
}
public System.Type GetAttributeType() {
return type;
}
public string GetLabel() {
return label;
}
}
using UnityEngine;
using UnityEditor;
using System.Collections;
[CustomPropertyDrawer(typeof(AssetPathAttribute))]
public class AssetPathPropertyDrawer : PropertyDrawer {
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
{
AssetPathAttribute attr = (AssetPathAttribute)attribute;
EditorGUI.BeginChangeCheck ();
Object o = null;
if(property.stringValue.Length != 0) {
string path = property.stringValue;
if(attr.isResource) {
path = "Assets/Resources/"+path;
if(attr.GetAttributeType() == typeof(Sprite)) {
} else {
path = path + ".prefab";
}
}
o = AssetDatabase.LoadAssetAtPath(path, attr.GetAttributeType());
}
o = EditorGUI.ObjectField(position, new GUIContent(attr.GetLabel()), o, attr.GetAttributeType(), false);
if (EditorGUI.EndChangeCheck ()) {
//property.stringValue = value;
string path = AssetDatabase.GetAssetOrScenePath(o);
if(attr.isResource) {
path = path.Replace("Assets/Resources/", "");
path = path.Replace(".prefab", "");
}
property.stringValue = path;
}
}
public override float GetPropertyHeight (SerializedProperty property, GUIContent label)
{
return base.GetPropertyHeight (property, label);
}
}
public class SomeData : ScriptableObject {
[AssetPathAttribute("Prefab", typeof(Object), true)]
public string prefabPath;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.