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

Unity运行时通过脚本为加载的FBX模型添加动画求助

运行时加载FBX模型并应用外部FBX动画(基于FBXImporter)

你已经成功用FBXImporter加载了模型,要给它应用另一个FBX的动画,可以按照以下步骤操作:

核心步骤

  1. 加载动画FBX文件,提取其中的动画剪辑
  2. 给加载的模型添加Animator组件
  3. 动态创建Animator Controller,将动画剪辑配置到状态机中
  4. 关联Animator与Controller,启动动画播放

完整代码示例

using UnityEngine;
using System.IO;

public class FBXLoader : MonoBehaviour
{
    public GameObject Eve;
    GameObject loadedModel;
    public static string modelPath = /* 模型FBX路径 */;
    public static string animPath = /* 动画FBX路径 */;

    void Start()
    {
        // 加载模型
        if (File.Exists(modelPath))
        {
            loadedModel = ModelImporter.Importer.Import(modelPath);
            loadedModel.transform.parent = Eve.transform;
            loadedModel.transform.localPosition = Vector3.zero;
            loadedModel.transform.localRotation = Quaternion.identity;
        }

        // 加载并应用动画
        if (loadedModel != null && File.Exists(animPath))
        {
            // 加载动画FBX
            GameObject animFbx = ModelImporter.Importer.Import(animPath);
            
            // 提取动画剪辑(FBXImporter会将动画存在Animation组件的clip中)
            Animation animComponent = animFbx.GetComponent<Animation>();
            if (animComponent != null && animComponent.clip != null)
            {
                AnimationClip animClip = animComponent.clip;
                
                // 给模型添加Animator组件
                Animator modelAnimator = loadedModel.AddComponent<Animator>();
                
                // 动态创建Animator Controller
                AnimatorController animController = AnimatorController.CreateAnimatorControllerAtPath("Assets/TempAnimController.controller");
                
                // 获取默认状态机,添加动画状态
                AnimatorStateMachine stateMachine = animController.layers[0].stateMachine;
                AnimatorState animState = stateMachine.AddState("DefaultAnim");
                animState.motion = animClip;
                
                // 关联Controller到Animator
                modelAnimator.runtimeAnimatorController = animController;
                
                // 自动播放动画
                modelAnimator.Play("DefaultAnim");
            }
        }
    }
}

注意事项

  • 确保模型和动画的骨骼结构匹配(Mixamo下载的模型和动画默认是匹配的,无需额外调整)
  • 动态创建的Animator Controller会保存在Assets/TempAnimController.controller,测试后可以根据需求调整路径或改为临时创建
  • 如果动画FBX包含多个剪辑,可以遍历animComponent.clips获取所有动画

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:15:53