Do Something on Animation End

I am playing an animation with the wrapMode of “Once”. As soon as the animation ends, I would like to CrossFade to another animation and execute some code. How can I achieve this?

I do this by setting a timer when I start the animation, so that the code gets executed at the end. I should mention that this is not exactly an ideal solution, but it works in most cases.

animation.CrossFade("anim", 0.3f);
StartCoroutine(WaitThenDoThings(animation["anim"].length));

IEnumerator WaitThenDoThings(float time)
{
    yield return new WaitForSeconds(time);

    // Now do some stuff...

    animation.CrossFade("anotherAnim", 0.5f);
    Debug.Log("Next Animation");
}

The problem here (a logical flaw, not a programmy one) is that you can’t really crossfade straight off the end of a ‘Once’ animationClip. It has to either clamp at the end, or you can start your crossfading a little before the end- in which case, you could do something like this-

animation.CrossFade("anim", 0.3f);
StartCoroutine(WaitThenCrossFade(animation["anim"], animation["nextAnim"], 0.3f));

IEnumerator WaitThenDoThings(AnimationState curAnim, AnimationState nextAnim, float time)
{
    yield return new WaitForSeconds(curAnim.length - time);

    // Now do some stuff...

    animation.CrossFade(nextAnim.name, time);
    Debug.Log("Fady animation");
}

Or you can check out something call Animation event in Unity, it really useful when we need to invoke function in the middle of animation http://unity3d.com/support/documentation/Components/animeditor-AnimationEvents.html