【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

效果截图

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

相关推荐
3D霸霸2 小时前
Sourcetree 拉取新工程
数据仓库·unity
程序员正茂4 小时前
Unity3d中RawImage显示视频画面偏白的解决方法
unity·视频·rawimage
mxwin5 小时前
Unity SetPassCall和DrawCall的区别是什么
unity·游戏引擎·shader
电子云与长程纠缠6 小时前
UE5 GameFeature创建与使用
开发语言·学习·ue5·游戏引擎
moonsims7 小时前
AiBrainLink:无人化系统异构连接架构-多执行体、多链路(5G+自组网)、多业务流(控制、遥测、视频、文件)透明传输、多对多控制
unity·游戏引擎
小贺儿开发7 小时前
Unity3D 年会抽奖工具(附体验链接)
数据库·unity·excel·人机交互·工具·抽奖·互动
旧物有情8 小时前
Unity性能优化之合批,什么是合批?
unity·性能优化·游戏引擎
天人合一peng1 天前
Hololens2 发布debug调试安装至hololens2
unity·xr
Yuk丶1 天前
UE4 与 UE5:技术差异深度解析
c++·ue5·游戏引擎·ue4·游戏程序·虚幻
l1t1 天前
DeepSeek总结的Delta 成长记:写入、Unity Catalog 和时间旅行
数据库·人工智能·unity