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

简介

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

代码示例(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

效果截图

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

相关推荐
派葛穆9 小时前
Unity-UI 输入框功能
ui·unity·游戏引擎
玖玥拾9 小时前
Unity3D RPG 入门项目(一)开场动画/人物移动/摄像机跟随场景切换
unity·游戏引擎
2401_8949155310 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity
WarPigs12 小时前
PC端加载安卓AB包资源显示紫色的问题
unity
scott.cgi14 小时前
Unity使用AndroidX获取,导航栏与虚拟键盘的高度
unity·androidx·keyboard·导航栏高度·虚拟键盘高度·判断键盘关闭·获取虚拟键盘高度
丁小未16 小时前
Unity车机地图Tile流式渲染系统高性能架构方案
unity·架构·ecs·dots·车机系统·车机系统架构图
LONGZETECH20 小时前
工业实训仿真设计实践:电机拆装软件的 DAG 流程建模、工具精度分级与数据体系搭建
大数据·算法·unity·架构·汽车
Python私教20 小时前
Godot 4 CharacterBody2D 角色移动:输入、碰撞与八方向控制实战
人工智能·游戏引擎·godot·gdscript·游戏开发
派葛穆2 天前
Unity-UI 按钮点击弹窗功能
unity·游戏引擎
toponad2 天前
Unity Ads Bidding 现已正式加入TopOn 聚合平台
unity·topon