Skip to content

Instantly share code, notes, and snippets.

@phosphoer
Created October 26, 2020 22:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phosphoer/40912ce692f1343d32b5d6e7fdbf4818 to your computer and use it in GitHub Desktop.
Save phosphoer/40912ce692f1343d32b5d6e7fdbf4818 to your computer and use it in GitHub Desktop.
Unity Animator Callbacks
using UnityEngine;
using System.Collections.Generic;
// Provides an interface to register callbacks for Animation Events, given they are named 'OnAnimEvent'
// with a string parameter defining the actual event name.
[RequireComponent(typeof(Animator))]
public class AnimatorCallbacks : MonoBehaviour
{
private Dictionary<string, System.Action> _callbacks = new Dictionary<string, System.Action>();
// Add a callback to the given event name
public void AddCallback(string eventName, System.Action callback)
{
System.Action eventCallback;
if (_callbacks.TryGetValue(eventName, out eventCallback))
{
eventCallback += callback;
_callbacks[eventName] = eventCallback;
}
else
{
_callbacks.Add(eventName, new System.Action(callback));
}
}
// Remove a callback from the given event name
public void RemoveCallback(string eventName, System.Action callback)
{
System.Action eventCallback;
if (_callbacks.TryGetValue(eventName, out eventCallback))
{
eventCallback -= callback;
_callbacks[eventName] = eventCallback;
}
}
public void ClearCallbacks(string eventName)
{
_callbacks.Remove(eventName);
}
// Called by sibling Animator
private void OnAnimEvent(string eventName)
{
System.Action eventCallback;
if (_callbacks.TryGetValue(eventName, out eventCallback))
{
eventCallback?.Invoke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment