【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

效果截图

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

相关推荐
weixin_409383121 小时前
godot 击败敌人后增加经验的脚本
游戏引擎·godot
海清河晏11112 小时前
数据结构 | 单链表
数据结构·unity·dreamweaver
mxwin14 小时前
Unity URP 下 MatCap 技术详解 无视光照环境的卡通与质感渲染方案
unity·游戏引擎
weixin_4093831214 小时前
godot 获取敌人位置自动发射子弹 旋转枪口
游戏引擎·godot
CDN36015 小时前
游戏盾日志看不到攻击?日志开启与上报问题排查
游戏·网络安全·游戏引擎
山檐雾1 天前
OctreeNode
unity·c#·八叉树
WarPigs1 天前
Unity协程返回值的解决方案
unity·游戏引擎
WarPigs2 天前
Unity单例笔记
unity·游戏引擎
风酥糖2 天前
Godot游戏练习01-第24节-多人游戏暂停菜单,游戏优化
游戏·游戏引擎·godot
Allen74743 天前
ComfyUI 自动化生产 3D资产 工作流笔记
图像处理·opencv·unity·自然语言处理·3d模型生成·confyui