이벤트 버스는 중앙에서 이벤트를 관리하는 시스템(버스)을 통해 이벤트를 발행하고 구독하는 패턴입니다. 이벤트를 발생시키는 객체와 이를 처리하는 객체가 서로 알 필요 없이 중앙화된 이벤트 관리 시스템에 의존합니다.
- 중앙 집중화: 모든 이벤트는 이벤트 버스라는 중앙 시스템을 통해 전달됩니다.
- 느슨한 결합: 발행자와 구독자가 서로를 알 필요가 없습니다.
- 전역 이벤트 처리: 이벤트가 글로벌하게 관리되므로 시스템의 여러 부분에서 쉽게 접근 가능.
- 단방향 흐름: 이벤트가 발행되면, 이를 구독한 모든 객체에 전달됩니다.
장점
- 이벤트를 중심으로 시스템이 느슨하게 결합되어 있음
- 다수의 이벤트를 중앙에서 관리 가능
- 여러 시스템(UI, 오디오, 로직 등)에서 같은 이벤트를 활용할 수 있음
단점
- 전역 관리로 인해 이벤트의 흐름이 복잡해질 경우 디버깅이 어려울 수 있음
- 구독 해제를 누락하면 메모리 누수가 발생할 수 있음 (꼭 Unsubscribe를 호출해야 함)
중앙관리 이벤트버스
using System;
using System.Collections.Generic;
public static class EventBus
{
// 이벤트 이름과 이를 처리할 델리게이트를 매핑
private static Dictionary<string, Action> events = new Dictionary<string, Action>();
// 이벤트 구독
public static void Subscribe(string eventName, Action listener)
{
if (!events.ContainsKey(eventName))
{
events[eventName] = listener;
}
else
{
events[eventName] += listener;
}
}
// 이벤트 구독 해제
public static void Unsubscribe(string eventName, Action listener)
{
if (events.ContainsKey(eventName))
{
events[eventName] -= listener;
// 더 이상 구독자가 없으면 이벤트 삭제
if (events[eventName] == null)
{
events.Remove(eventName);
}
}
}
// 이벤트 발행
public static void Publish(string eventName)
{
if (events.ContainsKey(eventName))
{
events[eventName]?.Invoke();
}
}
}
이벤트 구독 및 구독 해제
using UnityEngine;
public class UIManager : MonoBehaviour
{
private void OnEnable()
{
// 이벤트 구독
EventBus.Subscribe("OnScoreChanged", UpdateScoreUI);
}
private void OnDisable()
{
// 이벤트 구독 해제
EventBus.Unsubscribe("OnScoreChanged", UpdateScoreUI);
}
private void UpdateScoreUI()
{
Debug.Log("Score UI updated!");
// 실제 UI 업데이트 로직을 추가하면 됩니다.
}
}
이벤트 발행
using UnityEngine;
public class ScoreManager : MonoBehaviour
{
private int score = 0;
public void AddScore(int points)
{
score += points;
Debug.Log("Score added: " + points + ", Total Score: " + score);
// 이벤트 발행
EventBus.Publish("OnScoreChanged");
}
}
예제 테스트
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public ScoreManager scoreManager;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// 점수 추가
scoreManager.AddScore(10);
}
}
}
실행 흐름
- 플레이어가 스페이스바를 누르면 PlayerController에서 ScoreManager의 AddScore 메서드가 호출됩니다.
- AddScore는 점수를 추가한 후 "OnScoreChanged" 이벤트를 발행합니다.
- UIManager는 "OnScoreChanged" 이벤트를 구독하고 있으므로 UpdateScoreUI 메서드가 호출됩니다.
- 콘솔에 "Score UI updated!"가 출력되고, UI를 업데이트하는 로직을 실행합니다.