using UnityEngine; using UnityEngine.Events; using UnityEngine.Serialization; namespace R0bbie.Timeline.Events { /// /// Register to the linked GameEvent scriptable object, and trigger any function assign to the unity event /// [AddComponentMenu("Timeline/Game Events/Event Listener")] public class GameEventListener : MonoBehaviour, IGameEventListener { // Exposed Variables [Header("Event Listener")] public bool registerAutomatically = true; public bool triggerOnce; [Space(10)] [FormerlySerializedAs("animationStateEvent")] public GameEvent gameEvent; public UnityEvent response = new UnityEvent(); // Private Variables bool registered; bool triggered; void OnEnable() { if (!gameEvent) return; // If is not set to registered automatically, and haven't been registered yet, do nothing if (!registerAutomatically && !registered) return; // If already triggered, do nothing if (triggerOnce && triggered) return; Register(); } void OnDisable() { // If there is no game event attached at the moment the object is disabled, do nothing if (!gameEvent) return; // Unregister listener but remember status gameEvent.UnregisterListener(this); } public void OnEventRaised() { // If for some reason the event is still registered when it shouldn't, do nothing if (triggerOnce && triggered) return; triggered = true; response?.Invoke(); // Unregister and disable to avoid calling onDisable when unloading the level if (triggerOnce) Unregister(); } public void Register() { gameEvent.RegisterListener(this); registered = true; } public void Unregister() { gameEvent.UnregisterListener(this); registered = false; } } }