

public class EventBus : MonoBehaviour
{
private static EventBus eventbus;
public static EventBus Instance
{
get
{
if(eventbus == null)
{
GameObject go = new GameObject("EventBus"); //EventBus라는 빈 객체를 만들고
eventbus = go.AddComponent<EventBus>(); //EventBus 빈 객체에 EventBus 스크립트(컴포넌트)을 추가
Debug.Log("instance");
DontDestroyOnLoad(go);
}
return eventbus;
}
}
//go.AddComponent<EventBus>(); 하는 순간 Awake가 실행. 왜? 오브젝트(go)에 클래스(스크립트)을 추가하는 순간 해당 클래스의 인스턴스가 만들어지므로, 만들어지는 순간
//Awake가 실행된다.
private void Awake() //EventBus 스크립트(클래스)의 인스턴스가 만들어지는 순간 제일 먼저 실행. Awake는 생성자와 같은 타입
{
Debug.Log("Awake");
if(eventbus != null)
{
Destroy(gameObject);
}
else // 1. go.AddComponent<EventBus>(); -> 2. Awake 실행이므로 evetbus가 아직 null이다. 그래서 eventbus = this를 해준다.
{
eventbus = this;
}
}
}














using System;
using System.Collections.Generic;
using UnityEngine;
public static class EventBus
{
private static Dictionary<string, Action> eventDictionary = new Dictionary<string, Action>();
public static void Subscribe(string eventName,Action listener)
{
if(eventDictionary.ContainsKey(eventName))
{
eventDictionary[eventName] += listener;
}
else
{
eventDictionary[eventName] = listener;
}
}
public static void UnSubscribe(string eventName, Action listener)
{
if (eventDictionary.ContainsKey(eventName))
{
eventDictionary[eventName] -= listener;
if (eventDictionary[eventName] == null)
{
eventDictionary.Remove(eventName);
}
}
}
public static void Publish(string eventName)
{
if (eventDictionary.ContainsKey(eventName))
{
eventDictionary[eventName]?.Invoke();
}
else
{
Debug.Log($"해당 {eventName}는 eventDictionary의 존재하지 않는다.");
}
}
}
using UnityEngine;
public class TimeManager : SingleTonGeneric<TimeManager>
{
public static string OnDayStarted = "OnDayStartEvent"; //하루 일과 시작 될 때
public static string OnSlotChanged = "OnSlotChangeEvent"; //
public static string OnMiniGameEnded = "OnMiniGameEndEvent"; //하나의 미니게임이 끝났을 때
public static string OnDialogueEnded = "OnDialogueEndEvent"; //
protected override void Awake()
{
base.Awake();
}
private void Start()
{
StartDay();
}
public void StartDay() //하루 일과 시작
{
Debug.Log("TimeManager: 하루 일과 시작 - UI 업데이트");
EventBus.Publish(OnDayStarted);
}
}
using UnityEngine;
public class QuestManager : SingleTonGeneric<QuestManager>
{
protected override void Awake()
{
base.Awake();
}
private void OnEnable()
{
EventBus.Subscribe(TimeManager.OnDayStarted, OnDayStartHandler); //1.
}
private void OnDisable()
{
EventBus.UnSubscribe(TimeManager.OnDayStarted, OnDayStartHandler); //1.
}
private void OnDayStartHandler()
{
Debug.Log("QuestManager: 하루 시작에 대한 처리 - 미니게임 할당 부여");
}
}




구독자 스크립트에서 발행자의 클래스에 발행자 메서드를 호출하면 안된다.

QuestManager에서 TimeManager의 OnDayStartEvent를 구독하고 있다.


