【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

效果截图

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

相关推荐
又来07716 小时前
Unity手柄按键映射表
unity·游戏引擎
dzj202117 小时前
Unity的旁门左道用法(科学计算):用shader调用GPU做k线MA5的计算——DuckDB + Compute Shader
unity·金融·gpu·shader·量化·compute shader
世洋Blog17 小时前
Unity使用Luban的一些常用点
unity·游戏策划·luban
nnsix1 天前
Unity的dllType Native和Managed的区别
unity·游戏引擎
编码旅者1 天前
《Virt A Mate(VAM)》免安装豪华版v1.22中文汉化整合
游戏引擎·图形渲染·vr·动画
Clank的游戏栈1 天前
AI游戏开发全自动编程课程体系(Cursor版,支持Unity/Cocos, Laya后续支持)
人工智能·unity·游戏引擎
鹿野素材屋1 天前
技术闲聊:为什么网游会在固定时间点,刷出固定的道具?
前端·网络·unity
发际线危机121381 天前
Unity发布apk部分真机虚线采样变成实线问题
unity·游戏引擎
FVV11231 天前
电脑录屏工具Bandicam 无时长限制,支持4K画质
eclipse·游戏引擎·ar·动画·ogre
猫不吃咸鱼1 天前
Unity中攻击检测敌人的多种方法
游戏·unity·c#·游戏引擎