从不同的 AssetBundle 加载 Prefab 和 AnimationClips

Load Prefab and AnimationClips from different AssetBundle

我正在尝试从一个 AssetBundle 加载预制件并从另一个加载其对应的 AnimationClips。 至此从AssetBundle加载Prefab并Instantiate成功。

AssetBundle assetBundle = AssetBundle.LoadFromFile(path);
if (assetBundle == null) {
     return;
}

GameObject prefab = assetBundle.LoadAsset<GameObject>(name);
Instantiate(prefab, targetTransform.position, targetTransform.rotation);
assetBundle.Unload(false);

加载AnimationClips(Legacy animations)并将其添加到上面实例化的Gameobject中也成功了。

AssetBundle assetBundle = AssetBundle.LoadFromFile(path);
if (assetBundle == null) {
     return;
}

List<AnimationClip> animationClips = new List<AnimationClip>();
foreach (string name in names) {
     AnimationClip animationClip = assetBundle.LoadAsset<AnimationClip>(name);
     if (animationClip != null) {
        animationClips.Add(animationClip);
     }
}
assetBundle.Unload(false);

当我尝试播放动画时,它不工作而且我没有收到任何错误。

Animation animation = prefab.GetComponent<Animation>();

foreach (AnimationClip animationClip in animationClips) {
      string clipName = animationClip.name;
      animation.AddClip(animationClip, clipName);
}
foreach (AnimationClip animationClip in animationClips) {
      string clipName = animationClip.name;
      animation.PlayQueued(clipName, QueueMode.CompleteOthers);
}

我是否遗漏了什么或应该如何完成?

问题是您试图在预制件而不是实例化对象上播放动画:

GameObject prefab = assetBundle.LoadAsset<GameObject>(name);
//You instantiated object but did nothing with it. What's the point of the instantiation?
Instantiate(prefab, targetTransform.position, targetTransform.rotation);
//Don't do this. The Animation is attached to the prefab
Animation animation = prefab.GetComponent<Animation>();

当你调用Instantiate函数时,它会return实例化的对象。该 returned 对象是您应该用来获取 Animation 组件然后播放动画的对象。请注意,您的代码不完整,因此可能存在其他问题,但这也可能导致您遇到的问题。

GameObject prefab = assetBundle.LoadAsset<GameObject>(name);
//Instantiate the prefab the return the instantiated object
GameObject obj = Instantiate(prefab, targetTransform.position, targetTransform.rotation);
//Get the Animation component from the instantiated prefab
Animation animation = obj.GetComponent<Animation>();

现在,你可以玩了。