【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

效果截图

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

相关推荐
ThreePointsHeat1 小时前
Unity 关于打包WebGL + jslib录制RenderTexture画面
unity·c#·webgl
胡童嘉3 小时前
长沙烈焰鸟网络科技有限公司实习day13日记
功能测试·学习·职场和发展·游戏引擎·cocos2d
y***54886 小时前
C++在游戏引擎中的开发
开发语言·c++·游戏引擎
BuHuaX6 小时前
Unity_AssetBundle相关
unity·c#·游戏引擎·游戏策划
神码编程7 小时前
【Unity】 HTFramework框架(六十八)StringEditor字符串复杂编辑器
unity·编辑器·游戏引擎·htframework
开发游戏的老王8 小时前
UE5.6 C++项目升级UE5.7时用Rider加载项目失败的解决办法
ue5·游戏引擎·虚幻·虚幻引擎·rider·ue5.7·target.cs
TO_ZRG9 小时前
Unity-iPhone、Unity-Framework target 如何选择、@rpath报错
unity·ios·iphone
平行云17 小时前
World Labs & Paraverse:统一3D世界的创造与访问
3d·unity·ai·ue5·aigc·实时云渲染·云xr
jtymyxmz1 天前
《Unity Shader》7.2.3 实践 在切线空间下计算
unity·游戏引擎
在路上看风景1 天前
1.5 Material
unity