Assets/_Molca/_Core/Events/EventDispatcher.csSubsystem: registered with
RuntimeManager like other services
When to use
UseEventDispatcher when you need decoupled, cross-component communication without direct references:
- Cross-system notifications (e.g. language changed, app initialized, session events) where publisher and subscriber live in different assemblies or scenes.
- String-keyed events with optional typed payloads — avoids coupling to concrete event classes.
- Prefer
UnityEventfor Inspector-wired, single-object callbacks. Prefer C#eventfor tightly-coupled same-class patterns. UseEventDispatcherfor everything else.
API
| Method | Signature | Description |
|---|---|---|
RegisterEvent | void RegisterEvent(string eventName, Action callback) | Subscribe to a parameterless event |
RegisterEvent<T> | void RegisterEvent<T>(string eventName, Action<T> callback) | Subscribe to a typed-payload event |
UnregisterEvent | void UnregisterEvent(string eventName, Action callback) | Unsubscribe parameterless — call from OnDisable |
UnregisterEvent<T> | void UnregisterEvent<T>(string eventName, Action<T> callback) | Unsubscribe typed — call from OnDisable |
DispatchEvent | void DispatchEvent(string eventName) | Publish a parameterless event |
DispatchEvent<T> | void DispatchEvent<T>(string eventName, T eventData) | Publish a typed-payload event |
ClearEvent | void ClearEvent(string eventName) | Remove all handlers for a specific event |
ClearAllEvents | void ClearAllEvents() | Remove all handlers (called automatically on Shutdown) |
TypedEvents
File:Events/TypedEvents.cs — wraps common event names. Prefer these over magic strings where entries exist (scene load, modals, etc.).
Code
Use a normalMonoBehaviour with an injected EventDispatcher, subscribe in OnEnable, and always unsubscribe in OnDisable.
Troubleshooting
- Event not received: confirm
RegisterEventruns before the firstDispatchEvent. If subscription is inOnEnablebut dispatch fires duringRuntimeManagerinit, the handler may not be registered yet — move subscription toStartwithawait RuntimeManager.WaitForInitialization(). - Duplicate callbacks firing: calling
RegisterEventtwice with the same callback adds it twice viaDelegate.Combine. Always pair withUnregisterEventinOnDisableto prevent stacking across enable/disable cycles. - Missing unsubscribe causes errors after scene unload: destroyed objects’ callbacks remain registered and throw
MissingReferenceException. Always callUnregisterEventinOnDisableorOnDestroy. - Wrong type parameter on
DispatchEvent<T>: the type key must match exactly between publisher and subscriber.DispatchEvent<int>will not reachRegisterEvent<float>handlers even with the same event name.
Related
- RuntimeManager —
EventDispatcheris aRuntimeSubsystemon the prefab - Dependency injection — use
[Inject]to get the dispatcher - Localization — dispatches via
TypedEvents.LanguageChanged