Event bus system

From nlelouche/Unity-SkillForge · View interactive version

Event bus system is an AI agent skill from the GitHub repository nlelouche/Unity-SkillForge. Implements a global decoupled Event Bus for cross-system communication. Zero-allocation struct events prevent GC spikes.

How to use this skill

Skill file

Event Bus System

Overview

Implement global decoupled communication between systems using a static Event Bus. Uses struct-based events to avoid garbage collection allocations during gameplay.

When to Use

Architecture

┌──────────────┐    Publish(event)    ┌──────────────┐
│   Player     │ ───────────────────→ │   EventBus   │
│  (Publisher) │                      │   (Static)   │
└──────────────┘                      └───────┬──────┘
                                              │
              ┌───────────────────────────────┼───────────────────────────────┐
              ↓                               ↓                               ↓
      ┌───────────────┐              ┌───────────────┐              ┌───────────────┐
      │   HealthUI    │              │ AchievementSys│              │   Analytics   │
      │  (Subscriber) │              │  (Subscriber) │              │  (Subscriber) │
      └───────────────┘              └───────────────┘              └───────────────┘

Components

| Component | Purpose |

|-----------|---------|

| IEvent | Marker interface for all events |

| EventBus | Static class handling subscriptions |

| GameEvents.cs | Collection of event struct definitions |

| EventListenerBase<T> | Abstract MonoBehaviour for automatic lifecycle |

Procedure

  1. Define Events: Create structs implementing IEvent
  2. Publish Events: Call EventBus.Publish(new YourEvent { ... })
  3. Subscribe: Call EventBus.Subscribe<YourEvent>(HandleEvent) in OnEnable
  4. Unsubscribe: Call EventBus.Unsubscribe<YourEvent>(HandleEvent) in OnDisable

Best Practices

Event Definition Guidelines

// GOOD: Struct with relevant data
public struct EnemyKilledEvent : IEvent
{
    public readonly int EnemyId;
    public readonly Vector3 Position;
    public readonly int ExperienceReward;
}

// BAD: Class (causes allocation)
public class EnemyKilledEvent : IEvent { }

// BAD: Too much data
public struct EnemyKilledEvent : IEvent
{
    public Enemy FullEnemyReference; // Don't include references!
}

Few-Shot Examples

Example 1: UI Reacting to Damage

User: "Update health bar when player takes damage without coupling."

Agent:

// In PlayerHealth.cs
public void TakeDamage(float amount)
{
    _currentHealth -= amount;
    EventBus.Publish(new PlayerDamagedEvent 
    { 
        DamageAmount = amount,
        CurrentHealth = _currentHealth,
        MaxHealth = _maxHealth
    });
}

// In HealthBarUI.cs : EventListenerBase<PlayerDamagedEvent>
protected override void OnEventReceived(PlayerDamagedEvent evt)
{
    _slider.value = evt.CurrentHealth / evt.MaxHealth;
}

Example 2: Achievement System

User: "Unlock achievement when player kills 100 enemies."

Agent:

// Subscribe to EnemyKilledEvent
// Track kill count, check threshold, show achievement

Example 3: Sound Effects

User: "Play death sound when any enemy dies."

Agent:

// AudioManager subscribes to EnemyKilledEvent
// Plays sound at event.Position

TDD Contract

⚠️ Legacy Skill — Refactor Pending

Este skill NO tiene tests automatizados aún. El siguiente boilerplate es un punto de partida.

// Escribe estos tests ANTES de implementar:

// Test 1: should [expected behavior] when [condition]
[Test]
public void EventBusSystem_Should{ExpectedBehavior}_When{Condition}()
{{
    // Arrange
    // TODO: Setup test fixtures
    
    // Act
    // TODO: Execute system under test
    
    // Assert
    Assert.Fail("Not implemented — write test first");
}}

// Test 2: should handle [edge case]
[Test]
public void EventBusSystem_ShouldHandle{EdgeCase}()
{{
    // Arrange
    // TODO: Setup edge case scenario
    
    // Act
    // TODO: Execute
    
    // Assert
    Assert.Fail("Not implemented");
}}

// Test 3: should throw when [invalid input]
[Test]
public void EventBusSystem_ShouldThrow_When{InvalidInput}()
{{
    // Arrange
    var invalidInput = default;
    
    // Act & Assert
    Assert.Throws<Exception>(() => {{ /* execute */ }});
}}

Pasos para completar el TDD:

  1. Descomenta los tests above
  2. Implementa la funcionalidad mínima para que compile
  3. Ejecuta los tests — deben fallar (RED)
  4. Implementa la funcionalidad real
  5. Verifica que los tests pasen (GREEN)
  6. Refactorea manteniendo los tests verdes

Nota: Este skill fue marcado como tdd_first: false durante la auditoría v2.0.1. La sección TDD fue agregada automáticamente pero requiere customización manual para reflejar el comportamiento real del skill.

Related Skills

Template Files

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.