I'm trying to load Prefab from one AssetBundle and its corresponding AnimationClips from another. So far loading the Prefab from AssetBundle and Instantiate are successful.
AssetBundle assetBundle = AssetBundle.LoadFromFile(path);
if (assetBundle == null) {
return;
}
GameObject prefab = assetBundle.LoadAsset<GameObject>(name);
Instantiate(prefab, targetTransform.position, targetTransform.rotation);
assetBundle.Unload(false);
Loading AnimationClips (Legacy animations) and adding it to the above instantiated Gameobject are also successful.
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);
When I try to play the animation, it is not working and I'm not getting any error though.
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);
}
Am I missing anything or how it should be done?
The problem is that you're trying to play animation on the prefab instead of the instantiated object:
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>();
When you call the Instantiate
function, it will return the instantiated Object. That returned object is what you should use to get the Animation
component and then play your animation. Note that your code is not complete so there could be other issues but this one can also cause the issue you have.
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>();
Now, you can play it.