using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.SceneManagement; namespace OM { /// /// Interface for classes that require periodic updates. /// public interface IOMUpdater { bool IsDontDestroyOnLoad() => false; bool IsUpdaterCompleted(); void OnUpdate(); void Stop(); } /// /// Singleton class that manages and executes periodic updates for various components. /// public class OMUpdaterRuntime : MonoBehaviour { public const string GameObjectName = "HCCUpdaterRuntime"; public static OMUpdaterRuntime Instance { get; private set; } private readonly List _updaters = new List(); /// /// Initializes the singleton instance of the OMUpdaterRuntime. /// private void Awake() { if (Instance == null) { Instance = this; DontDestroyOnLoad(this); } else { Destroy(gameObject); } } /// /// Subscribes to the scene loaded event to stop updaters that are not marked as "DontDestroyOnLoad". /// private void OnEnable() { SceneManager.sceneLoaded += OnSceneLoaded; } /// /// Unsubscribes from the scene loaded event to prevent memory leaks. /// private void OnDisable() { SceneManager.sceneLoaded -= OnSceneLoaded; } /// /// Handles the scene loaded event and stops updaters that are not marked as "DontDestroyOnLoad". /// /// /// private void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode) { foreach (var updater in _updaters.Where(x => !x.IsDontDestroyOnLoad())) { updater.Stop(); } } /// /// Executes the update method for each registered updater. /// private void Update() { for (var i = _updaters.Count - 1; i >= 0; i--) { var updater = _updaters[i]; updater.OnUpdate(); if (updater.IsUpdaterCompleted()) { _updaters.RemoveAt(i); } } } /// /// Adds an updater to the list of updaters. /// /// public static void AddUpdater(IOMUpdater updater) { if (Instance == null) { Instance = new GameObject(GameObjectName).AddComponent(); } Instance._updaters.Add(updater); } /// /// Removes an updater from the list of updaters. /// /// public static void RemoveUpdater(IOMUpdater updater) { if(Instance == null) return; updater.Stop(); } } }