using UnityEngine;
namespace PlatypusIdeas.AirPath.Runtime.Events {
/// <summary>
/// Handles Update calls for the ScriptableObject-based EventBus
/// Attach this to a GameObject in your scene (preferably a persistent manager object)
/// </summary>
[DefaultExecutionOrder(-1000)]
public class EventBusUpdateHandler : MonoBehaviour {
[Header("Configuration")]
[SerializeField] private bool persistAcrossScenes = true;
[SerializeField] private PathfindingEventBus eventBusAsset;
[Header("Debug")]
[SerializeField] private bool showStatistics;
private static EventBusUpdateHandler _instance;
private void Awake() {
// Ensure only one instance exists
if (_instance != null && _instance != this) {
Destroy(gameObject);
return;
}
_instance = this;
// Make persistent if configured
if (persistAcrossScenes) {
DontDestroyOnLoad(gameObject);
}
// Validate and initialize the event bus
if (eventBusAsset == null) {
Debug.LogError("[EventBusUpdateHandler] No EventBus asset assigned! " +
"Please assign a PathfindingEventBus asset in the inspector.", this);
return;
}
// Set the singleton instance
PathfindingEventBus.SetInstance(eventBusAsset);
Debug.Log($"[EventBusUpdateHandler] PathfindingEventBus initialized successfully with asset '{eventBusAsset.name}'");
}
private void Update() {
// Process the event bus update
if (PathfindingEventBus.HasInstance) {
PathfindingEventBus.Instance.ProcessUpdate();
}
}
private void OnApplicationQuit() {
PathfindingEventBus.SetApplicationQuitting();
}
private void OnDestroy() {
if (_instance == this) {
_instance = null;
// Only set quitting if this is the actual application quit, not just scene change
if (!persistAcrossScenes || !Application.isPlaying) {
PathfindingEventBus.SetApplicationQuitting();
}
}
}
#if UNITY_EDITOR
private void OnValidate() {
// Editor-time validation
if (eventBusAsset == null) {
Debug.LogWarning($"[EventBusUpdateHandler] No EventBus asset assigned on '{gameObject.name}'. " +
"The EventBus will not work until you assign the asset.", this);
}
}
private void OnGUI() {
if (showStatistics && eventBusAsset) {
var stats = eventBusAsset.GetStatistics();
GUILayout.BeginArea(new Rect(10, 10, 300, 150));
GUILayout.BeginVertical("box");
GUILayout.Label("Event Bus Statistics", UnityEditor.EditorStyles.boldLabel);
GUILayout.Label($"Total Subscriptions: {stats.TotalSubscriptions}");
GUILayout.Label($"Queued Events: {stats.QueuedEvents}");
GUILayout.Label($"Event Types: {stats.EventTypes}");
GUILayout.Label($"Immediate Processing: {stats.IsProcessingImmediately}");
GUILayout.EndVertical();
GUILayout.EndArea();
}
}
#endif
}
}