You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity动画窗口自定义结构体分组动画失效问题求助

解决Unity Animation窗口自定义结构体字段分组问题

我之前也遇到过一模一样的情况——Unity默认只给命名为x/y/z的字段自动生成折叠分组,换成自定义字段名后这个功能就失效了。其实只要通过自定义属性抽屉(Property Drawer)就能实现和Vector3完全一致的分组效果,具体步骤如下:


1. 定义可序列化的自定义结构体

首先你的结构体必须标记[Serializable],确保Unity能序列化它的字段;如果字段是private的,记得加上[SerializeField]让动画系统能访问到:

using UnityEngine;
using System;

[Serializable]
public struct CustomVector
{
    // 这里替换成你想要的自定义字段名,比如Width/Height/Depth
    [SerializeField] public float Width;
    [SerializeField] public float Height;
    [SerializeField] public float Depth;
}

2. 创建自定义属性抽屉(Property Drawer)

在项目里新建一个Editor文件夹(必须叫这个名字,Unity才会识别为编辑器专用脚本),然后创建下面的脚本,用来让Unity编辑器把你的结构体渲染成可折叠的分组:

using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(CustomVector))]
public class CustomVectorDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        // 绘制折叠按钮,点击可以展开/收起字段
        property.isExpanded = EditorGUI.Foldout(position, property.isExpanded, label);
        
        if (property.isExpanded)
        {
            // 缩进子字段,让分组层级更清晰
            EditorGUI.indentLevel++;
            
            // 找到结构体里的三个自定义字段
            var widthProp = property.FindPropertyRelative("Width");
            var heightProp = property.FindPropertyRelative("Height");
            var depthProp = property.FindPropertyRelative("Depth");
            
            // 依次绘制每个字段,调整位置避免重叠
            EditorGUI.PropertyField(new Rect(position.x, position.y + 18, position.width, 16), widthProp);
            EditorGUI.PropertyField(new Rect(position.x, position.y + 36, position.width, 16), heightProp);
            EditorGUI.PropertyField(new Rect(position.x, position.y + 54, position.width, 16), depthProp);
            
            EditorGUI.indentLevel--;
        }
    }

    // 动态调整属性高度,折叠时只占一行,展开后占四行
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return property.isExpanded ? 18 * 4 : 18;
    }
}

3. 在脚本中使用自定义结构体

把你的自定义结构体作为公开字段(或带[SerializeField]的私有字段)放在MonoBehaviour脚本里:

public class AnimatedObject : MonoBehaviour
{
    public CustomVector MyCustomVector;
}

做完这些操作后回到Unity编辑器,你会发现Animation窗口里的MyCustomVector字段会像Vector3一样,有一个下拉箭头可以展开/收起你自定义的Width/Height/Depth字段,完全符合你的需求!

额外注意点:

  • 编辑器脚本一定要放在Editor文件夹下,否则会在打包时报错。
  • 如果你的结构体字段是private的,必须加[SerializeField],不然动画系统无法识别和编辑这些字段。

内容的提问来源于stack exchange,提问作者TVOHM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:41:55