Last active
February 6, 2025 09:51
-
-
Save sunnybolter/8e42e48bd2cef63a6a888186428952a3 to your computer and use it in GitHub Desktop.
AnimationEventsHandler for Unity
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
/* | |
This code defines a system for handling animation-related events in Unity. | |
This system can be used to trigger animation-related actions, | |
such as playing sounds, activating game objects, | |
or running custom logic when an animation reaches a specific frame. | |
*/ | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using UnityEngine; | |
using UnityEngine.Events; | |
[Serializable] | |
public class AnimationEvent | |
{ | |
[SerializeField] private string name; | |
[SerializeField] private UnityEvent action; | |
public string Name => name; | |
public event Action OnAnimationEvent; | |
public void InvokeEvents() | |
{ | |
OnAnimationEvent?.Invoke(); | |
action?.Invoke(); | |
} | |
} | |
public class AnimationEventsHandler : MonoBehaviour | |
{ | |
[SerializeField] private List<AnimationEvent> animationEvents; | |
public AnimationEvent GetEventByName(string name) | |
{ | |
return animationEvents?.FirstOrDefault(e => string.Equals(e.Name, name)); | |
} | |
public void TriggerEvent(string name) | |
{ | |
GetEventByName(name)?.InvokeEvents(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment