AnmationEvent has no receiver! error

I have a GameObject that adds an AnimationEvent to a clip that calls a function at completion of the animation. It calls this function reliably – until I destroy the game object. I destroy the object when I detect a collision and I am careful to call Animation.Stop() before I destroy the object, so the end function callback should not be called, but appears to be. My worry is that Unity might still try to call the function even if I stop the animation early, but by that time the object is gone.

The relevant code:

function BeginIdleAnimation() {
	if (idleAnimation) {
		var repeat : boolean = idleAnimation.wrapMode == WrapMode.Loop 
			|| idleAnimation.wrapMode == WrapMode.PingPong;
		PlayAnimationClip(idleAnimation, repeat ? "IdleAnimDone" : null);
		PlayClip(idleSound);
	}
}

function PlayAnimationClip(clip : AnimationClip, endFunc : String) {
	if (clip) {
		// create event that calls desired endFunc when animation completes
	 	if (endFunc) {
	 	    var event : AnimationEvent = new AnimationEvent();
	  	    event.functionName = endFunc;
	  	    event.time = clip.length; 
	   	    clip.AddEvent(event);
	   	}
	    animation.clip = clip;
	    animation.Play();
	}
}

// Here's the relevant snippet of collision code that supposedly stops the animation before destroying itself...

function OnCollision(p : Projectile) {
	if (p) {
		animation.Stop();
		Destroy(transform.parent.gameObject);
	}
}

function IdleAnimDone() {
	PlayClip(idleSound);
}

I get “AnimationEvent ‘IdleAnimDone’ has no receiver!” error.

Thanks in advance!

oddly enough, AnimationEvent seems to use SendMessage, and CANT send AnimationEvent Calls to an animation component on a different object(in the hierarchy). You MUST, apparently, from the bit I researched( I could be wrong, but just reproduced this error and fix in a test scene), issue those AnimationEvent calls to an animation component(holding your anim clips) on the same object as the script issuing the AnimationEvent calls.

Make your animation event call on the SAME object that has the ANIMATION COMPONENT you are adding the events to, and then you dont need to perform the dontRequireReceiver option as well. SendMessage can have requirements on which direction in the hierarchy it will send the message to :wink:

It pays to read the documentation, huh? This solves the problem:

AnimationEvent ae = new AnimationEvent();
ae.messageOptions = SendMessageOptions.DontRequireReceiver;

Another way this can happen is if the component is removed from the animated object (or someone on your team doesn’t check the addition of the component to the prefab into version control but does check in the animation change).

I noticed that when it put my event in the top event field it added in

protected virtual void OnAttack( string attackType )

but had the word NewEvent in front. So it was

NewEvent protected virtual void OnAttack( string attackType )