【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

效果截图

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

相关推荐
公爵爱学习8 小时前
无人机多点巡航
游戏引擎·无人机·cocos2d
公爵爱学习9 小时前
关于无人机定点飞行的一些解释和Matlab程序绘制
游戏引擎·无人机·cocos2d
wgslucky1 天前
Godot GDScript初学者遇到的问题记录
游戏引擎·godot
点心的游戏开发世界1 天前
GDScript 入门笔记(五):函数
笔记·游戏引擎·godot
谢斯1 天前
[unity]如何在unity中添加newtonsoft-json
unity·json·游戏引擎
天人合一peng1 天前
Unity标记固定颜色及投影标记
unity
云雨巫山1 天前
Unity 游戏开发性能优化全景手册
unity·智能手机·性能优化·游戏引擎
maybeyaluokenai1 天前
unity build in渲染管线概述
unity·图形渲染
学习星球1 天前
AI 原生游戏开发:Godot 4 + AI Agent 全栈指南(Ziva 3 / Godot MCP 深度实战)
人工智能·游戏引擎·godot
云雨巫山1 天前
Unity 性能优化 · 图解全景手册
unity·性能优化·游戏引擎