我正在尝试从一个AssetBundle中加载Prefab,并从另一个中加载其对应的AnimationClip。 到目前为止,从AssetBundle和Instantiate加载Prefab成功。
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(旧版动画)并将其添加到上面实例化的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);
}
我错过了什么吗?应该怎么做?
答案 0 :(得分:2)
问题是您正在尝试在预制而不是实例化的对象上播放动画:
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
函数时,它将返回实例化的Object。返回的对象是您用来获取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>();
现在,您可以播放它了。