【Attribute】Inspector视图可视不可编辑字段特性

简介

在Unity开发中,有时候我们存在这种需求,需要在Inspector视图中可以查看字段信息但是无法对字段进行赋值,那么我们也可以像Unity内置的[SerializeField]、[Tooltip]等特性那样自定义一个特性,用于满足这个需求。

代码示例(C#)

cs 复制代码
#if UNITY_EDITOR
using System;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

// 禁用可序列化字段在Inspector面板的编辑
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public class EditDisabledAttribute : PropertyAttribute { }

// EditDisabledAttribute的自定义绘制器
[CustomPropertyDrawer(typeof(EditDisabledAttribute))]
class EditDisabledDrawer : 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)
    {
        if (IsArray() || IsList())
        {
            EditorGUI.BeginDisabledGroup(true);
            EditorGUI.PropertyField(position, property, label, true);
            EditorGUI.EndDisabledGroup();
        }
        else
        {
            GUI.enabled = false;
            EditorGUI.PropertyField(position, property, label, true);
            GUI.enabled = true;
        }
    }

    // 是否为数组
    private bool IsArray()
    {
        return fieldInfo.FieldType.IsArray;
    }

    // 是否为列表
    private bool IsList()
    {
        return fieldInfo.FieldType.IsGenericType && fieldInfo.FieldType.GetGenericTypeDefinition() == typeof(List<>);
    }
}
#endif

效果截图

如果这篇文章对你有帮助,请给作者点个赞吧

相关推荐
Doc.S3 小时前
多无人机任务自定义(基于ZJU-FAST-Lab / EGO-Planner-v2)
游戏引擎·无人机·cocos2d
那个村的李富贵4 小时前
Unity打包Webgl后 本地运行测试
unity·webgl
nnsix5 小时前
Unity OpenXR开发HTC Vive Cosmos
unity·游戏引擎
nnsix5 小时前
Unity OpenXR,扳机键交互UI时,必须按下扳机才触发
unity·游戏引擎
nnsix6 小时前
Unity XR 编辑器VR设备模拟功能
unity·编辑器·xr
老朱佩琪!6 小时前
Unity访问者模式
unity·游戏引擎·访问者模式
不定时总结的那啥6 小时前
Unity实现点击Console消息自动选中预制体的方法
unity·游戏引擎
nnsix6 小时前
Unity OpenXR 关闭手柄的震动
unity·游戏引擎
CreasyChan7 小时前
Unity 中的反射使用详解
unity·c#·游戏引擎·游戏开发
Jessica巨人7 小时前
Shader显示为黑色
unity·shader