Files
UnityPackages/Assets/Common/Timer/Runtime/ScriptableObjects/TimerBaseSO.cs
2025-12-01 12:36:01 +08:00

113 lines
2.8 KiB
C#

using System;
using TriInspector;
using UnityEditor;
using UnityEngine;
namespace Common.Timer.Runtime.ScriptableObjects
{
public abstract class TimerBaseSO : ScriptableObject, ITimer
{
protected abstract ITimer Timer { get; }
public bool IsActive => Timer.IsActive;
public float CurrentTime
{
get => Timer.CurrentTime;
set => Timer.CurrentTime = value;
}
public float DeltaTime => Timer.DeltaTime;
public void Tick() => Timer.Tick();
public void Activate(bool resetTime = false)
{
AddToManager();
Activate_Internal(resetTime);
}
public void Deactivate() => Timer.Deactivate();
public void ResetTime() => Timer.ResetTime();
public virtual void SetTime(float value)
{
CurrentTime = value;
}
public event Action OnTick
{
add => Timer.OnTick += value;
remove => Timer.OnTick -= value;
}
public event Action OnActivate
{
add => Timer.OnActivate += value;
remove => Timer.OnActivate -= value;
}
public event Action OnDeactivate
{
add => Timer.OnDeactivate += value;
remove => Timer.OnDeactivate -= value;
}
public event Action OnTimeReset
{
add => Timer.OnTimeReset += value;
remove => Timer.OnTimeReset -= value;
}
protected abstract void Activate_Internal(bool resetTime = false);
private void AddToManager()
{
if (!TimerManager.GetInstance()) TimerManager.CreateInstance();
TimerManager.Instance.Add(this);
}
private void RemoveFromManager()
{
if (!TimerManager.GetInstance()) return;
TimerManager.Instance.Remove(this);
}
#if UNITY_EDITOR
protected virtual void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (state == PlayModeStateChange.ExitingPlayMode)
{
Reinitialize();
}
}
#endif
#if UNITY_EDITOR
protected virtual void OnValidate()
{
if (!EditorApplication.isPlaying) Timer.Deactivate();
}
#endif
protected virtual void OnEnable()
{
#if UNITY_EDITOR
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
#endif
}
protected virtual void OnDisable()
{
#if UNITY_EDITOR
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
#endif
}
protected virtual void OnDestroy()
{
#if UNITY_EDITOR
Reinitialize();
#endif
}
[Button]
public abstract void Reinitialize();
}
}