Created
October 26, 2020 22:31
-
-
Save phosphoer/40912ce692f1343d32b5d6e7fdbf4818 to your computer and use it in GitHub Desktop.
Unity Animator Callbacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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