114 lines
3.0 KiB
C#
114 lines
3.0 KiB
C#
using System;
|
|
using TriInspector;
|
|
using UnityEngine;
|
|
using UnityEngine.Serialization;
|
|
|
|
namespace Common.Timer.Runtime
|
|
{
|
|
/// <summary>
|
|
/// C# implementation of a timer. Remember to call Tick() on this Timer object via script!
|
|
/// </summary>
|
|
[Serializable]
|
|
[DeclareBoxGroup("Debug")]
|
|
[DeclareBoxGroup("Internal")]
|
|
public class Timer : ITimer
|
|
{
|
|
[Title("Settings")]
|
|
[SerializeField]
|
|
[FormerlySerializedAs("_isActive")]
|
|
protected bool isActive;
|
|
public virtual bool IsActive
|
|
{
|
|
get => isActive;
|
|
protected set => isActive = value;
|
|
}
|
|
|
|
protected float currentTime;
|
|
[Group("Internal"), ShowInInspector, DisableInEditMode]
|
|
public virtual float CurrentTime
|
|
{
|
|
get
|
|
{
|
|
currentTime = Mathf.Max(currentTime, 0f);
|
|
return currentTime;
|
|
}
|
|
set => currentTime = Mathf.Max(value, 0f);
|
|
}
|
|
[Group("Internal"), ShowInInspector, DisableInEditMode]
|
|
public virtual float DeltaTime => Time.deltaTime;
|
|
|
|
public event Action OnTick;
|
|
public event Action OnActivate;
|
|
public event Action OnDeactivate;
|
|
public event Action OnTimeReset;
|
|
|
|
public Timer(bool isActive)
|
|
{
|
|
this.isActive = isActive;
|
|
}
|
|
|
|
#region Public Methods
|
|
|
|
public virtual void Tick()
|
|
{
|
|
if (!IsActive) return;
|
|
|
|
CurrentTime += DeltaTime;
|
|
InvokeOnTick();
|
|
}
|
|
|
|
public virtual void Activate(bool resetTime = false)
|
|
{
|
|
IsActive = true;
|
|
InvokeOnActivate();
|
|
if (resetTime) ResetTime();
|
|
}
|
|
|
|
public virtual void Deactivate()
|
|
{
|
|
IsActive = false;
|
|
InvokeOnDeactivate();
|
|
}
|
|
|
|
public virtual void ResetTime()
|
|
{
|
|
CurrentTime = 0f;
|
|
InvokeOnTimeReset();
|
|
}
|
|
|
|
public virtual void SetTime(float value)
|
|
{
|
|
CurrentTime = value;
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Protected Methods
|
|
|
|
protected virtual void InvokeOnTick() => OnTick?.Invoke();
|
|
protected virtual void InvokeOnActivate() => OnActivate?.Invoke();
|
|
protected virtual void InvokeOnDeactivate() => OnDeactivate?.Invoke();
|
|
protected virtual void InvokeOnTimeReset() => OnTimeReset?.Invoke();
|
|
|
|
#endregion
|
|
|
|
#if UNITY_EDITOR
|
|
|
|
[Group("Debug"), Button("Activate"), HideInEditMode]
|
|
private void Activate_Editor() => Activate(false);
|
|
|
|
[Group("Debug"), Button("Activate (Reset Time)"), HideInEditMode]
|
|
private void ActivateResetTime_Editor() => Activate(true);
|
|
|
|
[Group("Debug"), Button("Deactivate"), HideInEditMode]
|
|
private void Deactivate_Editor() => Deactivate();
|
|
|
|
[Group("Debug"), Button("Tick"), HideInEditMode]
|
|
private void Tick_Editor() => Tick();
|
|
|
|
[Group("Debug"), Button("Reset Time"), HideInEditMode]
|
|
private void ResetTime_Editor() => ResetTime();
|
|
|
|
#endif
|
|
}
|
|
} |