【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

效果截图

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

相关推荐
gshh__1 天前
SuperMap Hi-Fi 3D SDK for Unreal 如何修改模型选中高亮颜色
ue5·游戏引擎·supermap
沉默金鱼2 天前
Unity实用技能-GM命令
unity·游戏引擎
chillxiaohan2 天前
unity粗糙、高光、光泽度调节shader记录
unity·游戏引擎
星夜泊客2 天前
Unity UI 渲染与 Rebuild 机制简易解析
unity·游戏引擎
一线灵2 天前
跨平台游戏引擎 Axmol-2.11.1 发布
游戏引擎
qiminixi2 天前
Unity 6000下载
unity·unity 6000·unity 6000下载
CreasyChan2 天前
Unity Shader 入门指南
unity·c#·游戏引擎·shader
漂视数字孪生世界2 天前
Unity团结引擎的前世今生
unity·游戏引擎·数字孪生
心前阳光3 天前
Unity通过ScriptableObject学习访问者模式
学习·unity·访问者模式
fcm193 天前
unity之重新导入TMP
unity