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>();

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.


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.

The short answer is: when first import the model to Unity, you MUST select animation type to be ‘Legacy’ in Rig Tab, like this . 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.