Access animation clip (by index or by name)
I added an Animation component to a gameobject, then set the size of animations to 3, then assigned the animation clips to the 3 slots.
--. First I try to access the animations this way,
public Animation[] anim;
anim = gameObject.GetComponents<Animation>();
anim[0].Play();
anim[1].Play();
But I will get error when it reaches anim[1]
IndexOutOfRangeException: Index was outside the bounds of the array.
I guess I can't access their array?
--. Then I tried to build my own array
public Animation[] anim;
Then set the anim size to 3 in inspector, I'm UNABLE to assign animation clips to the slots in script component....
--. Lastly I tried access animation clip by it's name: "Armature|idle01",etc.
gameObject.GetComponent<Animation>().Play("Armature|idle01");
I get error: The animation state Armature|idle01 could not be played because it couldn't be found! Please attach an animation clip with the name 'Armature|idle01' or call this function only for existing animations.
I'm seriously confused.
Answer by unity_bfawXRcvR563OA · Jun 22, 2019 at 10:24 AM
The short answer is: when first import the model to Unity, you MUST select animation type to be 'Legacy' in Rig Tab, like this https://docs.unity3d.com/Manual/Animations.html . This is the ONLY way to add 'animation' component properly. Or you have to use Animator.
--Otherwise, if you manually create animation component and assign animation clips, or create your own array and assign animation clips, you either get 'animation State could not be played because it couldn't be found! ' or a 'Null reference' error, or you can play animations just fine in Unity Editor, but NOT ON DEVICE.
--Using animation component will allow you to access animation by name using the same line of code (such as anim.Play("idle")), when you have different prefabs (with same animation names, such as 'idle' 'run' ) assigned with same script.
Thanks this helped me. If you have a bunch of animation clips and you do not want to type the names manually then. Create an array with the animation clips and order them same as in the Animation component. Now you can ask for the animation clip name from that array when you want to pass the animation name string to the animcomp.Play("Clipname");
Your answer
Follow this Question
Related Questions
Animation stops playing as soon as AnimationClip.AddEvent is used 0 Answers
Sprites & Animation 1 Answer
How do get access to animation clips in selected model from EditorWindow? 0 Answers
How to change the animation speed of a certain animation clip within a blend tree by C# script 0 Answers
Any way to set AnimatorOverrideController's animation clips programatically? 1 Answer