【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

效果截图

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

相关推荐
LF男男3 小时前
IBuilder.cs 接口
unity
心之所向,自强不息4 小时前
# Unity MCP + Codex CLI 完整教程(Windows)
windows·unity·游戏引擎
KillJUMP5 小时前
GODOT SHADER关键函数
游戏引擎·godot
Oiiouui8 小时前
Godot(4.x): Python处理转换Excel为注入Json
游戏引擎·godot
追光者♂10 小时前
【测评系列3】CSDN AI数字营销实测体验官:测试 开源项目——Superpowers 游戏引擎从零开发实战指南
人工智能·深度学习·机器学习·typescript·开源·游戏引擎·superpowers
小拉达不是臭老鼠10 小时前
Unity数据持久化_Json
学习·unity
heimeiyingwang10 小时前
【架构实战】订单系统架构设计:电商核心系统的演进
unity·架构·系统架构
元气少女小圆丶11 小时前
SenseGlove Nova 2+Unity开发笔记3
笔记·unity·游戏引擎
Oiiouui11 小时前
Godot(4.x): 游戏管理器: Excel 动态依赖注入实现
游戏·游戏引擎·godot
WMX101211 小时前
Unity-shader学习记录
学习·unity·游戏引擎