Unity动态加载和添加动画控制器

3

我的代码现在:

Animator ContainerAnimator = this.GetComponent<Animator>();
ContainerAnimator.runtimeAnimatorController = Resources.Load("Assets/Cube") as RuntimeAnimatorController;
ContainerAnimator.Play("ContainerMoveUp");

我有一些动态创建的对象,其中包含动画。这些动画仍然没有控制器,我正在尝试添加控制器,但似乎不起作用。有什么技巧或提示可以解决这个问题吗?谷歌上的答案已经不够用了。


你把动画控制器放在哪里了? - Programmer
直接放在资产文件夹中。 - Sten Martens
它的名字是什么? - Programmer
2个回答

2

Resources.Load("Cube") 很可能会返回 null。

  1. 您必须将动画控制器放置在名为“Resources”的文件夹中,该文件夹位于 Assets 文件夹中。请注意正确拼写。将您的动画控制器移动到此“Resources”文件夹中。

  2. 之后,从 Resources.Load 函数中删除 “Assets/”。应传递相对于 Resources 文件夹的路径。

如果动画控制器名称为“Cube”,则可以这样加载它:

Resources.Load("Cube")

替代:

Resources.Load("Assets/Cube")

0

你可能从错误的目录加载了资源或者文件名错放了位置。在这里,你只需要从代码中删除 Assets/ 前缀即可解决问题。

你也可以尝试以下实现方式。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayAnimationDemo : MonoBehaviour
{
    [SerializeField]  
    Animator anim; // refer the animator via inspector

    void Start() {
        PlayAnimation(anim, "Cube", "ContainerMoveUp");
    }

    // animator is the animator object referred via inspector
    // fileName is the animator controller file name which should put under the Resources folder
    // animName is the animation clip name, you want to play
    void PlayAnimation(Animator animator, string fileName, string animName) {
        animator.runtimeAnimatorController = Resources.Load(fileName) as RuntimeAnimatorController;
        animator.Play(animName);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接