【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

效果截图

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

相关推荐
浅陌sss12 小时前
Unity中可靠的UDP实现
unity
虾球xz15 小时前
游戏引擎学习第107天
学习·游戏引擎
虾球xz15 小时前
游戏引擎学习第105天
前端·学习·游戏引擎
奔跑的犀牛先生18 小时前
unity学习46:反向动力学IK
unity
幻世界20 小时前
【工具插件类教学】实现运行时2D物体交互的利器Runtime2DTransformInteractor
unity·交互·运行时2d物体交互
虾球xz1 天前
游戏引擎学习第104天
学习·游戏引擎
音视频牛哥2 天前
Unity实现高性能多实例RTSP|RTMP播放器技术实践
unity·游戏引擎·音视频·实时音视频·大牛直播sdk·rtsp播放器·rtsp player
Artistation Game2 天前
三、Unity基础(主要框架)
游戏·unity·c#·游戏引擎
Edision_li2 天前
DeepSeek教unity------MessagePack-03
unity·messagepack
lalapanda2 天前
Unity学习part2
学习·unity·游戏引擎