Giter VIP home page Giter VIP logo

unity-event-bus's Introduction

Unity C# Event Bus

EventBus

Description

This EventBus system provides a way to create decoupled architectures in Unity projects. It allows communication between different parts of an application without requiring direct references.

Code Structure

This EventBus system contains several C# classes residing in the Scripts\EventBus directory:

  1. EventBus.cs - Main EventBus class that provides static functions for registering, deregistering, and triggering custom events.

  2. EventBinding.cs - IEventBinding interface and class definition for EventBinding, which is used to bind functions to events.

  3. Events.cs - IEvent interface and sample code, which shows how to define custom events.

  4. PredefinedAssemblyUtil.cs - Utility class for locating assemblies and finding types within them. See Unity Documentation.

  5. EventBusUtil.cs - Static initialization methods and additional utilities used for EventBus.

Example Usage

The usage generally works like:

public struct PlayerEvent : IEvent {
    public int health;
    public int mana;
}

EventBinding<PlayerEvent> playerEventBinding;

void OnEnable() {    
    playerEventBinding = new EventBinding<PlayerEvent>(HandlePlayerEvent);
    EventBus<PlayerEvent>.Register(playerEventBinding);

    // Can Add or Remove Actions to/from the EventBinding
}

void OnDisable() {
    EventBus<PlayerEvent>.Deregister(playerEventBinding);
}

void Start() {
    EventBus<PlayerEvent>.Raise(new PlayerEvent {
        health = healthComponent.GetHealth(),
        mana = manaComponent.GetMana()
    });    
}

void HandlePlayerEvent(PlayerEvent playerEvent) {
    Debug.Log($"Player event received! Health: {playerEvent.health}, Mana: {playerEvent.mana}");
}

YouTube

Watch the tutorial video here

You can also check out my YouTube channel for more Unity content.

Installation and Setup

Since this is a Unity-centric project, you will need to have Unity installed on your system. The EventBus codebase is entirely C# and conforms to the .NETFramework v4.7.1 standards.

To use these scripts in your project, please place these scripts in your Scripts or a related directory in the Unity editor.

Contributions

Contributions are always welcome. You can contribute by improving the EventBus codebase, enhancing its features, or providing suggestions.

Inspired by

This project takes inspiration from the following open source projects:

unity-event-bus's People

Contributors

adammyhre avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

unity-event-bus's Issues

Why use an EventBinding class?

Hey Adam!

Thank you for your great content!
I implemented your EventBus but think it is more complex than necessary.
Is there a specific reason why you work with the EventBinding class? In my eyes this only leads to more verbose code without any benefits. Do you extend the EventBinding class with additional functionality or why did you choose to go that way?

Example of registering a binding with your implementation:

private EventBinding<PlayerEvent> _playerEventBinding;
private void OnEnable()
{
    _playerEventBinding = new EventBinding<PlayerEvent>(HandlePlayerEvent);
    EventBus<PlayerEvent>.Register(_playerEventBinding);
}

With the implementation below it would be just one line:

private void OnEnable()
{
    EventBus<PlayerEvent>.Register(HandlePlayerEvent);
}

My EventBus implementation:

public static class EventBus<T> where T : IEvent
{
    //in this case we specifically _want_ a static member in a generic type. We want a different bindings-hashSet in each instance of different close constructed type (https://www.jetbrains.com/help/resharper/StaticMemberInGenericType.html)
    // ReSharper disable once StaticMemberInGenericType
    private static readonly HashSet<Action> BindingsWithoutArguments = new();
    private static readonly HashSet<Action<T>> BindingsWithArguments = new();
    
    public static void Register(Action<T> binding) => BindingsWithArguments.Add(binding);
    public static void Register(Action binding) => BindingsWithoutArguments.Add(binding);

    public static void DeRegister(Action<T> binding) => BindingsWithArguments.Remove(binding);
    public static void DeRegister(Action binding) => BindingsWithoutArguments.Remove(binding);

    public static void Raise(T @event)
    {
        foreach (Action<T> binding in BindingsWithArguments)
        {
            binding?.Invoke(@event);
        }

        foreach (Action binding in BindingsWithoutArguments)
        {
            binding?.Invoke();
        }
    }

    /// <summary>Remove all listeners.</summary>
    [UsedImplicitly] //used via reflection in EventBusUtilities.ClearAllBuses()
    public static void Clear()
    {
        Debug.Log($"{EventBusUtilities.EventBusLogPrefix}Clearing {typeof(T).Name} bindings (removing all listeners)");
        BindingsWithArguments.Clear();
        BindingsWithoutArguments.Clear();
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.