【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

效果截图

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

相关推荐
奔跑的犀牛先生1 小时前
unity学习26:用Input接口去监测: 鼠标,键盘,虚拟轴,虚拟按键
unity
Dr.勿忘11 小时前
C#面试常考随笔8:using关键字有哪些用法?
开发语言·unity·面试·c#·游戏引擎
存储服务专家StorageExpert12 小时前
答疑解惑:如何监控EMC unity存储系统磁盘重构rebuild进度
运维·unity·存储维护·emc存储
Petrichorzncu14 小时前
Games104——游戏引擎Gameplay玩法系统:基础AI
游戏引擎
追逐梦想永不停18 小时前
Unity实现按键设置功能代码
unity
我命由我123451 天前
游戏引擎 Unity - Unity 下载与安装
c语言·开发语言·c++·后端·unity·c#·游戏引擎
车载诊断技术1 天前
车载软件架构 --- 基于AUTOSAR软件架构的ECU开发流程小白篇
网络·unity·架构·汽车·电子电器框架·车载充电器(obc)
我命由我123451 天前
游戏引擎 Unity - Unity 启动(下载 Unity Editor、生成 Unity Personal Edition 许可证)
c语言·c++·后端·unity·c#·游戏引擎·ue4
我命由我123452 天前
游戏开发领域 - 游戏引擎 UE 与 Unity
开发语言·c++·unity·c#·游戏引擎·unreal engine·unreal engine 4
一个一定要撑住的学习者2 天前
Day29(补)-【AI思考】-精准突围策略——从“时间贫困“到“效率自由“的逆袭方案
人工智能·unity·游戏引擎