1. EventBus 구현 EventBus.cs 파일 using System;
using System.Collections.Generic; public static class EventBus { private static readonly Dictionary<Type, Delegate> events = new Dictionary<Type, Delegate>(); public static void Subscribe<T>(Action<T> listener) { if (events.TryGetValue(typeof(T), out var del)) events[typeof(T)] = (Action<T>)del + listener; else events[typeof(T)] = listener; } public static void Unsubscribe<T>(Action<T> listener) { if (!events.TryGetValue(typeof(T), out var del)) return; var current = (Action<T>)del - listener; if (current == null) events.Remove(typeof(T)); else events[typeof(T)] = current; } public static void Publish<T>(T evt) { if (events.TryGetValue(typeof(T), out var del)) ((Action<T>)del)?.Invoke(evt); } } 2. Event 정의 PlayerScoreEvent.cs 파일 public class PlayerScoredEvent
{ public int Score { get; private set; } public PlayerScoredEvent(int score) { Score = score; } } 3. 이벤트 구독 using UnityEngine;
public class ScoreManager : MonoBehaviour { void OnEnable() { EventBus.Subscribe<PlayerScoredEvent>(OnPlayerScored); } void OnDisable() { EventBus.Unsubscribe<PlayerScoredEvent>(OnPlayerScored); } void OnPlayerScored(PlayerScoredEvent e) { Debug.Log("Score: " + e.Score); } } 4. 이벤트 발행 EventBus.Publish(new PlayerScoredEvent(10));
이벤트가 매우 많으면 메모리 누수 체크는 꼭 필요 (Unsubscribe 반드시!) |