Last active
December 5, 2022 18:37
-
-
Save japsuu/a04d4658d4080951dac1d5668f532d8d to your computer and use it in GitHub Desktop.
Radio event system 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
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); | |
} | |
} | |
} |
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 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