【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

效果截图

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

相关推荐
风酥糖6 小时前
Godot游戏练习01-第12节-添加武器动画,同步动画显示
游戏·游戏引擎·godot
斯幽柏雷科技1 天前
[Unity]Inspector各种写法(持续更新中)
java·unity·游戏引擎
林鸿群1 天前
Cocos2d-x v4 官方文档学习总结
学习·游戏引擎·cocos2d
林鸿群1 天前
Cocos2d-x 官方仓库学习总结
学习·游戏引擎·cocos2d
毕竟秋山澪1 天前
unity Skill接入TraeAI操作步骤
unity·游戏引擎
XR-AI-JK1 天前
01-VR开发如何配置和搭建基础环境
unity·vr·vr基础教程·vr教程·vr实战教程·vr节奏游戏·unityvr教程
派葛穆1 天前
Unity-生成预制体1
unity
WarPigs1 天前
Unity CG着色器实战
unity·着色器
废嘉在线抓狂.1 天前
TimeLine如何自定义轨道
unity·c#·对话系统