【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

效果截图

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

相关推荐
玖玥拾15 分钟前
Cocos学习笔记:序列化、配置文件与数据驱动
游戏引擎·cocos2d
RReality34 分钟前
【Unity UGUI】血条 / 进度条(HP Bar)
ui·unity·游戏引擎·图形渲染
mxwin8 小时前
Unity Shader URP:法线如何进行光照计算
unity·游戏引擎·shader
郝学胜-神的一滴9 小时前
中级OpenGL教程 009:用环境光告别模型死黑
前端·c++·unity·godot·图形渲染·opengl·unreal
一锅炖出任易仙11 小时前
创梦汤锅学习日记day30
学习·ai·ue5·游戏引擎
mxwin20 小时前
Unity URP 中的法线生成完全指南
unity·游戏引擎
游乐码20 小时前
Unity基础(十五)LineRender画线功能
unity·游戏引擎
玖玥拾21 小时前
Cocos学习笔记:瓦片地图与坐标转换
游戏引擎·cocos2d
小贺儿开发1 天前
Unity3D 图片循环查看器
unity·工具·图片·列表·循环·ugui·互动
晓13131 天前
【Cocos Creator 3.x】篇——第二章 入门
前端·javascript·游戏引擎