Unity--PropertyAttribute和PropertyDrawer结合使用将string转为资源引用

代码如下:

using UnityEngine;

public class PropertyTest : MonoBehaviour
{
    public string prefabPath = "";
}

prefabPath表示引用的prefab路径,在Inspector中显示如下图

这种情况需要手动填写prefab的路径,填错prefab路径程序运行就找不到prefab了,下面通过

PropertyAttribute和PropertyDrawer结合,在Inspector中显示出来的是资源引用,直接弹出面板选择prefab

using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(PrefabReference))]
public class ResReferenceDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (SerializedPropertyType.String != property.propertyType)
        {
            EditorGUI.PropertyField(position, property);
            return;
        }

        //根据路径得到一个类型为GameObject的对象
        var prefab = (GameObject)AssetDatabase.LoadAssetAtPath(property.stringValue, typeof(GameObject));
        //ObjectField会在Inspector面板中显示一个框,后面带一个小按钮,点击后弹出面板选择prefab
        var obj = (GameObject)EditorGUI.ObjectField(position, property.displayName, prefab, typeof(GameObject), false);
        //得到prefab的路径
        string newPath = AssetDatabase.GetAssetPath(obj);
        //设置路径
        property.stringValue = newPath;
        Debug.Log(newPath);
    }
}

效果如图,可以点击后面按钮弹出面板选择,也可以直接拖拽prefab进行设置

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值