Animation doesn't work properly

I want to play an animation to a player when it enters to a 2D trigger, but the animation plays all the time, not only when colliding.

I’ve written this script:

var playanimation : boolean = false;

function OnTriggerEnter2D (other : Collider2D)
{

if (!playanimation)
{

if(gameObject.tag == “Finish”)
{

playanimation = true;

yield WaitForSeconds (3);

playanimation = false;

}

}

}

function Update ()
{

if(playanimation == true)
{

animation.Play (“invencible”);

}

}

I think that the problem also can be that the animation is attached to a wrong gameobject, but I’m not sure (i’ve tryed several combinations, but no one work, I have to learn in all that…).

i think u have two solutions:

1 - set the wrap mode of the animation “invencible” to once in the project view or in the start callback like this:

function Start()
{
    animation["invencible"].wrapMode = WrapMode.Once;
}

2 - if u want the animation clip to play always until u stop it just make the wrap mode to loop and then check when the boolean value is false:

if(playanimation == false) 
{
     animation.Stop("invencible");
}

one last thing, insure to uncheck “Play Automatically” in the g.o that has the animation attached

Are you using the old animation component? Or does the component in the editor say “animator” instead?
If it says “animator” then you have the two mixed up. The animation component is the old way and it is going to be phased out in the future. The animator component is a state machine basically and you’ll have to use the animator code.
Also, if you are indeed using the animation component in the editor, check that your animation is set to “legacy” and that you don’t the looping option on.