# Can't play animation from script in unity

I'm making a 2D sidescrolling game in Unity, and when the player shoots an obstacle, I want the obstacle animation to play and then destroy itself. I got it to destroy itself, but the animation won't play. Any suggestions?

    public class obstacleAnim : MonoBehaviour {

protected Animation obsanim;

// Use this for initialization
void Start () {
obsanim = GetComponent<Animation> ();
}

void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "circle")
{
obsanim.Play ("circobs");
Destroy (gameObject, 1.0f);
}
}
}


thank you for any help!

I tested your script and it works as expected. The problem is most likely the animation itself. You should enable autoplay from the Animation component and see if your animation works without the script. Also make sure there are no errors in the console. Click the error counter in case you have accidentally hidden them.

• The animation worked fine before I implemented the script, but now it won't play I don't know why – Jordan Dec 27 '14 at 20:17
• I added a picture – Jordan Dec 27 '14 at 20:25
• @Jordan From this picture, it looks like you have both an Animator and an Animation component on the object. These two may be fighting for control of the object's animation behaviour. What happens if you get rid of the Animator? – DMGregory Jun 9 '15 at 19:33
• Check if the tag is really the same and that the right collision occurred – Vadim Tatarnikov Sep 8 '15 at 11:59

Did you try not to Destroy the object at the moment when you play the animation? wait until the animation is finished.

i hope it helps!

• The second parameter of the Destroy function is a delay, for exactly that purpose, so this answer doesn't add anything the asker hasn't already tried. – DMGregory Jun 9 '15 at 12:45