using System; using UnityEngine; namespace OM { /// /// A simple ticker class that triggers an action at specified intervals. /// public class OMTicker : IOMUpdater { /// /// Creates a new OMTicker instance. /// /// /// /// /// /// public static OMTicker Create( float interval, Action onTick, bool timeIndependent = false, bool persist = false) { var ticker = new OMTicker(interval,onTick,timeIndependent,persist); return ticker; } private readonly Action _onTick; private readonly float _interval; private readonly bool _persist; private readonly bool _timeIndependent; private int _tickCount; private float _timer; public bool IsRunning { get; private set; } = true; /// /// Constructor for the OMTicker class. /// /// /// /// /// private OMTicker(float interval, Action onTick,bool timeIndependent,bool persist = false) { _interval = interval; _timeIndependent = timeIndependent; _onTick = onTick; _persist = persist; OMUpdaterRuntime.AddUpdater(this); } /// /// Gets the delta time based on the time-independent setting. /// /// private float GetDeltaTime() { return _timeIndependent ? Time.unscaledDeltaTime : Time.deltaTime; } /// /// Checks if the ticker is set to persist across scenes. /// /// public bool IsDontDestroyOnLoad() { return _persist; } /// /// Checks if the ticker is time-independent. /// /// public bool IsUpdaterCompleted() { return !IsRunning; } /// /// Updates the ticker and invokes the tick action if the interval has passed. /// public void OnUpdate() { _timer += GetDeltaTime(); if(_timer >= _interval) { _timer -= _interval; _tickCount++; _onTick?.Invoke(_tickCount); } } /// /// Stops the ticker from running. /// public void Stop() { IsRunning = false; } } }