【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

效果截图

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

相关推荐
淡海水11 小时前
【节点】[IrisOutOfBoundColorClamp节点]原理解析与实际应用
unity·游戏引擎·iris·shadergraph·图形·clamp·bound
风痕天际16 小时前
Godot扫雷游戏制作记录1——基础场景搭建
游戏·游戏引擎·godot·gdscript·教程
上证50指数etf18 小时前
Unity面试总结
unity
爱搞虚幻的阿恺1 天前
Niagara粒子系统-超炫酷的闪电特效(第二期 旋转的纸片)
游戏·游戏引擎·虚幻
WarPigs2 天前
Unity渲染问题记录
unity·游戏引擎
不绝1912 天前
导入3D模型时相关参数设置/Model标签页/Rig标签页/Avatar相关参数/Animation标签页/Materia标签页
unity·游戏程序
dlpay2 天前
使用blender搭建模型并导入godot游戏引擎
游戏引擎·godot·blender
不是AI2 天前
【Unity开发】一、在安卓设备上运行Unity项目
android·unity·游戏引擎
淡海水2 天前
【节点】[EyeSurfaceTypeDebug节点]原理解析与实际应用
unity·游戏引擎·debug·shadergraph·图形·surface·eye
淡海水3 天前
【节点】[IrisLimbalRing节点]原理解析与实际应用
unity·游戏引擎·iris·shadergraph·图形·ring·limbal