How do I remove an object after an animation has played?

So, I’ve been writing some code for a collectable ‘Key’ in my game. The goal you must reach does not appear until this key is collected, to create a kind of secondary objective.

An animation plays when this key is touched that makes it shrink, and I want it to be destroyed after that to make the goal appear. Although, the object is always destroyed before the animation gets a chance to start.

Here’s the code I’m using.

if (other.gameObject.CompareTag ("Key")) {
			Animation shrink = other.gameObject.GetComponent<Animation>();
			shrink.Play ();
			if (shrink.isPlaying == (false))
				Destroy (other.gameObject);
		}

In your code, you are destroying the animation right away after calling Play(). So it always goes away.

One solution is to destroy the game object after the animation finishes playing: The second parameter to Destroy (below) will destroy the game object after that many seconds have elapsed. In the example below, I’m passing in the length of the animation clip, which will probably work. You may want to add a little (+ 0.1) just to be sure.

if ( other.gameObject.CompareTag("Key"))
    {
        Animation shrink = other.gameObject.GetComponent<Animation>();
        shrink.Play();
        Destroy(other.gameObject, shrink.clip.length);
    }