Skip to content
Snippets Groups Projects
GameEventListener.cs 2.27 KiB
using System;
using UnityEngine;
using UnityEngine.Events;

namespace Shared.ScriptableVariables {
  // Component to tie GameEvents to Unity's event system
  public class GameEventListener : MonoBehaviour {
    [Tooltip("The game event to listen to")]
    public GameEvent eventToListenTo;

    [Tooltip("The UnityEvent to raise in response to the game event being raised")]
    public UnityEvent response;

    //---------------------------------------------------------------------------
    void OnEnable() {
      eventToListenTo.OnRaised += OnEventRaised;
    }

    //---------------------------------------------------------------------------
    void OnDisable() {
      eventToListenTo.OnRaised -= OnEventRaised;
    }

    //---------------------------------------------------------------------------
    public virtual void OnEventRaised() {
      if (response != null) {
        try {
          response.Invoke();
        }
        catch (Exception exception) {
          Debug.LogError($"{gameObject.name} is throwing the following exception:");
          Debug.LogException(exception);
        }
      }
    }
  }

  //---------------------------------------------------------------------------
  public abstract class GameEventListener<T> : MonoBehaviour {
    //---------------------------------------------------------------------------
    protected abstract GameEvent<T> GetGameEvent();

    //---------------------------------------------------------------------------
    protected abstract UnityEvent<T> GetUnityEvent();

    //---------------------------------------------------------------------------
    void OnEnable() {
      GetGameEvent().OnRaised += OnEventRaised;
    }

    //---------------------------------------------------------------------------
    void OnDisable() {
      GetGameEvent().OnRaised -= OnEventRaised;
    }

    //---------------------------------------------------------------------------
    public virtual void OnEventRaised(T value) {
      var unityEvent = GetUnityEvent();
      if (unityEvent != null) {
        try {
          unityEvent.Invoke(value);
        }
        catch (Exception exception) {
          Debug.LogError($"{gameObject.name} is throwing the following exception:");
          Debug.LogException(exception);
        }
      }
    }
  }
}