【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

效果截图

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

相关推荐
qq_2052790517 分钟前
Unity log工具 Unity Logviewer插件
unity·游戏引擎
IMPYLH2 小时前
Lua 的 tonumber 函数
开发语言·笔记·后端·junit·游戏引擎·lua
tealcwu3 小时前
【Unity实战】如何使用VS Code在真实iOS设备上调试 Unity应用
unity·游戏引擎·iphone
冰凌糕8 小时前
Unity3D Shader 顶点和片段着色器
unity
Echo_NGC22378 小时前
【AirSim 教程指南】Part 3:相机与传感器(RGB / 深度 / 分割 / LiDAR)
人工智能·计算机视觉·游戏引擎·ar·无人机·图形渲染·着色器
tealcwu11 小时前
【Unity实战】如何使用VS Code在真实Android设备上调试 Unity应用
android·unity·游戏引擎
IMPYLH11 小时前
Lua 的 setmetatable 函数
开发语言·笔记·后端·游戏引擎·lua
淡海水1 天前
【节点】[Blackbody节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·blackbody
avi91111 天前
Unity-海水效果+ShaderGraph-非专业不谈虚的效果-分享实用Editor源码
unity·游戏引擎
猫不在1 天前
MVC和MVVM
unity