Unity编辑器中的只读属性

在unity的开发过程中,有时候会出现这样的需求,自定义的组件中存在public字段,但是又不想开放给非程序组的同学编辑,为了防止其误操作,需要将字段设置成只读状态,如上图中的TestValue01字段。

当然,可以通过给每个组件自定义Inspector实现这样的需求,但是这样做怎么想都感觉不是太合理。下面提供一种更优雅的写法:

1.定义一个只读属性:

using UnityEngine;
namespace Tools
{
    public class ReadonlyAttribute : PropertyAttribute
    {
    }
}

2.实现自定义属性的GUI绘制:

using Tools;
using UnityEditor;
using UnityEngine;

namespace Editor.Tools
{
    [CustomPropertyDrawer(typeof(ReadonlyAttribute))]
    public class ReadonlyAttributeDrawer : PropertyDrawer
    {
        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            return EditorGUI.GetPropertyHeight(property, label, true);
        }

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            //禁用GUI,使字段不可用
            EditorGUI.BeginDisabledGroup(true);
            EditorGUI.PropertyField(position, property, label, true);
            //恢复GUI字段
            EditorGUI.EndDisabledGroup();
        }
    }
}

3.用法:

using Tools;
using UnityEngine;

public class TestAttribute : MonoBehaviour
{
    [Readonly]
    public int testValue01;
    public int testValue02;
} 
posted @ 2025-06-29 17:25  小·糊涂仙  阅读(40)  评论(0)    收藏  举报