Skip to content

Instantly share code, notes, and snippets.

@Fenikkel
Last active March 21, 2025 10:01
Show Gist options
  • Save Fenikkel/803fb8fa5564a4a7306693c1012dbb58 to your computer and use it in GitHub Desktop.
Save Fenikkel/803fb8fa5564a4a7306693c1012dbb58 to your computer and use it in GitHub Desktop.
Event bus

Static event bus

 

Event bus example

 

Notes

Simple tu use and foolproof. It uses abstraction to make it almost invisible on your code and easy to reuse it.

 

Usage (no arguments)

  1. Add an enum memeber to BusEvent enum:
  public enum BusEvent
  {
      PlayerLevelUp,
      CloseMenu
      // Add event name here...
  }
  1. Subscribe:
        Action levelUpAction = OnPlayerLevelUp;
        EventBus.Subscribe(BusEvent.PlayerLevelUp, levelUpAction);
  1. Raise:
        EventBus.Raise(BusEvent.PlayerLevelUp);
  1. Unsubscribe:
        EventBus.Unsubscribe(BusEvent.PlayerLevelUp, levelUpAction);

 

Usage (with arguments)

  1. Create a class that inherids EventBusArg):
public class CustomEventArg : EventBusArg
{
}
  1. Set up your event arguments
public class CustomEventArg : EventBusArg
{
    /* Parametters set up */
    public int IntParametter { get; private set; }
    public bool BooleanParametter { get; private set; }


    /* Arguments set up */
    public CustomEventArg(int parametterOne = 1, bool parametterTwo = false)
    {
        IntParametter = parametterOne;
        BooleanParametter = parametterTwo;
    }
}
  1. Subscribe:
        Action<CustomEventArg> customEventAction = OnCustomEvent;
        EventBus.Subscribe<CustomEventArg>(customEventAction);
  1. Raise:
        EventBus.Raise(new CustomEventArg(5));
  1. Unsubscribe:
        EventBus.Unsubscribe<CustomEventArg>(customEventAction);

 

Compatibility

  • Any Unity version
  • Any pipeline (Build-in, URP, HDRP, etc)

 

Credit

These scripts are a modifyed version of Freedom Coding codes.

 

Support

⭐ Star if you like it
❤️️ Follow me for more

public enum BusEvent
{
EventNameOne,
EventNameTwo
// Add event name here...
}
using System;
using System.Collections.Generic;
using UnityEngine;
/* Enum-based */
public static partial class EventBus
{
static Dictionary<BusEvent, Action> _AssignedActions = new();
public static void Raise(BusEvent eventName)
{
if (_AssignedActions.TryGetValue(eventName, out Action existingAction))
{
Debug.AssertFormat(existingAction != null,$"Trying to raise a null action subscribed to <b>{eventName}</b>");
existingAction?.Invoke();
}
else
{
Debug.LogWarning($"Can't <b>raise</b> the <b>{eventName}</b> because it's not subscribed.");
}
}
public static void Subscribe(BusEvent eventName, Action action)
{
if (action == null)
{
Debug.LogWarning($"Trying to subscribe a null Action to <b>{eventName}</b>");
return;
}
if (_AssignedActions.ContainsKey(eventName))
{
_AssignedActions[eventName] += action;
}
else
{
_AssignedActions[eventName] = action;
}
}
public static void Unsubscribe(BusEvent eventName, Action action)
{
if (action == null)
{
Debug.LogWarning($"Trying to <b>un</b>subscribe a null Action to <b>{eventName}</b>");
return;
}
if (_AssignedActions.ContainsKey(eventName))
{
_AssignedActions[eventName] -= action;
if (_AssignedActions[eventName] == null) // No actions remaining
{
_AssignedActions.Remove(eventName);
}
}
else
{
Debug.LogWarning($"Can't <b>unsubscribe</b> the <b>{eventName}</b> because it doesn't exist or it's already unsubscribed.");
}
}
}
public class EventBusArg
{
// You can force parametters for all events here
}
using System;
using System.Collections.Generic;
using UnityEngine;
/* Type-based */
public static partial class EventBus
{
static Dictionary<Type, Delegate> _AssignedDelegates = new();
public static void Raise(EventBusArg data)
{
Type type = data.GetType();
if (_AssignedDelegates.TryGetValue(type, out Delegate existingDelegate))
{
Debug.AssertFormat(existingDelegate != null, $"Trying to raise a null Delegate with arguments of type <b>{type}</b>");
existingDelegate?.DynamicInvoke(data);
}
else
{
Debug.LogWarning($"Can't <b>raise</b> the arguments <b>{type}</b> because there are no subscriptions for it.");
}
}
public static void Subscribe<T>(Action<T> action) where T : EventBusArg
{
Type type = typeof(T);
if (action == null)
{
Debug.LogWarning($"Trying to subscribe a null Action with arguments of type <b>{type}</b>");
return;
}
if (_AssignedDelegates.ContainsKey(type))
{
_AssignedDelegates[type] = Delegate.Combine(_AssignedDelegates[type], action);
}
else
{
_AssignedDelegates[type] = action;
}
}
public static void Unsubscribe<T>(Action<T> action) where T : EventBusArg
{
Type type = typeof(T);
if (action == null)
{
Debug.LogWarning($"Trying to <b>un</b>subscribe a null Action with arguments of type <b>{type}</b>");
return;
}
if (_AssignedDelegates.ContainsKey(type))
{
_AssignedDelegates[type] = Delegate.Remove(_AssignedDelegates[type], action);
if (_AssignedDelegates[type] == null) // No actions remaining
{
_AssignedDelegates.Remove(type);
}
}
else
{
Debug.LogWarning($"Can't <b>unsubscribe</b> the <b>{action.Method.Name}</b> because it doesn't exist or it's already unsubscribed.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment