2
\$\begingroup\$

enter image description hereI'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!

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ The animation worked fine before I implemented the script, but now it won't play I don't know why \$\endgroup\$ – Jordan Dec 27 '14 at 20:17
  • \$\begingroup\$ I added a picture \$\endgroup\$ – Jordan Dec 27 '14 at 20:25
  • 1
    \$\begingroup\$ @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? \$\endgroup\$ – DMGregory Jun 9 '15 at 19:33
  • \$\begingroup\$ Check if the tag is really the same and that the right collision occurred \$\endgroup\$ – Vadim Tatarnikov Sep 8 '15 at 11:59
-2
\$\begingroup\$

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!

\$\endgroup\$
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – DMGregory Jun 9 '15 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.