Skip to content

Instantly share code, notes, and snippets.

@japsuu
Last active December 5, 2022 18:37
Show Gist options
  • Save japsuu/a04d4658d4080951dac1d5668f532d8d to your computer and use it in GitHub Desktop.
Save japsuu/a04d4658d4080951dac1d5668f532d8d to your computer and use it in GitHub Desktop.
Radio event system for Unity
using System.Collections.Generic;
using UnityEngine;
namespace Framework.EventSystem
{
[CreateAssetMenu(menuName="EventChannel", fileName="EventChannel_")]
public class EventChannel : ScriptableObject
{
[SerializeField] private List<EventListener> listeners = new();
public void Raise(object data = null)
{
for (int i = listeners.Count -1; i >= 0; i--)
{
listeners[i].OnEventRaised(data);
}
}
public void RegisterListener(EventListener listener)
{
if (!listeners.Contains(listener))
listeners.Add(listener);
}
public void UnregisterListener(EventListener listener)
{
if (listeners.Contains(listener))
listeners.Remove(listener);
}
}
}
using UnityEngine;
using UnityEngine.Events;
namespace Framework.EventSystem
{
[System.Serializable]
public class EventResponse : UnityEvent<object> {}
public class EventListener : MonoBehaviour
{
[Tooltip("Channel to listen to.")]
public EventChannel listenedChannel;
[Tooltip("Response to invoke when an event is raised.")]
public EventResponse response;
private void OnEnable()
{
listenedChannel.RegisterListener(this);
}
private void OnDisable()
{
listenedChannel.UnregisterListener(this);
}
public void OnEventRaised(object data)
{
response.Invoke(data);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment