【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

效果截图

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

相关推荐
归真仙人8 小时前
【UE】UMG安卓相关问题
android·ue5·游戏引擎·ue4·虚幻·unreal engine
BuHuaX9 小时前
Unity项目怎么接入抖音小游戏?
unity·c#·游戏引擎·wasm·游戏策划
Sator110 小时前
unity Rayfire破碎插件的踩坑点
unity·游戏引擎
鱼蛋-Felix11 小时前
C#浮点数在部分国家解析失效问题
开发语言·unity·c#
_风华ts12 小时前
虚幻引擎碰撞相关的属性
游戏引擎·虚幻·collision
龚子亦13 小时前
【Jenkins】实现Unity远程自动化打包
unity·自动化·jenkins
_风华ts1 天前
虚幻引擎RPC
rpc·游戏引擎·虚幻
垂葛酒肝汤1 天前
放置挂机游戏的离线和在线收益unity实现
游戏·unity·c#
孟无岐1 天前
【Laya】Base64Tool 编码工具类使用说明
typescript·游戏引擎·游戏程序·laya
康de哥1 天前
在OpenCode中配置unity3d-mcp
unity·glm-4.7·minimax m2.1·opencode·unity3d-mcp