Adding Animation Event to a clip where the called function is not on the game object

Hello everyone,

A bit of context to what I am trying to do. I have a lot of animations scattered over different game objects and I would like to have only 1 playing at a time. To attempt this, I created an animation manager that queues up any animation requests and keeps track if an animation is playing. However to determine when an animation has finished playing, I need to add an event to the end of the clip and I haven’t figured out how to make that event call a function on my animation manager.

Here’s some sample code

public void PlayAnimation(Animator animator, string trigger, string animationName){

//Get the clip by searching by name
AnimationClip[] clips = animator.runtimeAnimatorController.animationClips;

foreach (AnimationClip clip in animator.runtimeAnimatorController.animationClips) {
      if (clip.name == animationName) {
		AnimationEvent evt = new AnimationEvent();
		evt.time = clip.length;
		evt.functionName = "DonePlaying"; //AnimationEvent 'DonePlaying' has no receiver!
		clip.AddEvent(evt);
	        }
         }

			animator.SetTrigger(trigger);
			playingAnimation = true;
		}
	}

  //Function somewhere else in the animation manager
	public void DonePlaying(){
		playingAnimation = false;
	}

Is this possible to do this? Ideally I would like to specify the receiver for this animation event so I can tell it where the DonePlaying function is. Adding a script with a DonePlaying function to every single object that has an animation would defeat the purpose of having an animation manager.

I could add a coroutine in the manager that does a WaitForSeconds(clip.length) and then flips the playingAnimation flag but that seems like a very hacky approach and there must be a better way to do this.

The documentation clearly says that these events work like SendMassage, which traverse the gameobjects monobehaviours and calls on the first found receiver. I think you have two options here. You either define monobehaviours with predefined functions which you add right before the manager adds the AnimationEvent to the clip. Or you use some kind of translater for the objectReferenceParameter you can use. Within that you could put strings and such to distinguish between different methods that should be called, or objects that need to be searched for or…

I’d prefer the first version. Whenever a receiver function is needed, you just attach the monobehaviour containing it to the animator if it does not exist, initiliaze it with itself so the function can call back to the manager. You could even have a track count for deletion after it’s not needed anymore.