using System;
using System.Collections.Generic;
namespace BulletHellTemplate.Core.Events
{
///
/// Simple global event bus that allows publishing and subscribing to strongly typed events.
///
public static partial class EventBus
{
private static readonly Dictionary> _subscribers = new();
///
/// Subscribe to a specific event type.
///
public static void Subscribe(Action callback)
{
var type = typeof(T);
if (!_subscribers.ContainsKey(type))
_subscribers[type] = new List();
_subscribers[type].Add(callback);
}
///
/// Unsubscribe from a specific event type.
///
public static void Unsubscribe(Action callback)
{
var type = typeof(T);
if (_subscribers.TryGetValue(type, out var list))
{
list.Remove(callback);
if (list.Count == 0)
_subscribers.Remove(type);
}
}
///
/// Publish an event to all listeners of the event type.
///
public static void Publish(T publishedEvent)
{
var type = typeof(T);
if (_subscribers.TryGetValue(type, out var list))
{
foreach (var callback in list)
{
if (callback is Action action)
action.Invoke(publishedEvent);
}
}
}
///
/// Clears all subscribers from the bus. Use carefully!
///
public static void ClearAll()
{
_subscribers.Clear();
}
}
}