【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

效果截图

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

相关推荐
jtymyxmz29 分钟前
《Unity Shader》10.2.1 镜子效果
unity·游戏引擎
ellis197031 分钟前
Unity打开新项目Package相关报错处理记录
unity
微:xsooop2 小时前
iOS 上架4.3a 审核4.3a 被拒4.3a 【灾难来袭】
flutter·unity·ios·uniapp
微光守望者2 小时前
Unity ScriptableObject详解:优化游戏架构的强大工具
unity·游戏引擎
jtymyxmz3 小时前
《Unity Shader》10.2.2 玻璃效果
unity·游戏引擎
zxc2446039346 小时前
gpu instancer crowd 动画使用方式
unity
C MIKE7 小时前
unity资源下载
unity
Avalon7127 小时前
Unity中自定义协程的实现
游戏·unity·c#·游戏引擎
IMPYLH8 小时前
Lua 的 select 函数
java·开发语言·笔记·后端·junit·游戏引擎·lua
jtymyxmz9 小时前
《Unity shader》10.1.5 菲涅尔反射
unity·游戏引擎