BITKit/Packages/Runtime/SubSystems/Timer/TimerSystem.cs

61 lines
1.8 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.TestTools;
namespace BITKit
{
using SubSystems;
public class BITTimer
{
internal BITTimer() { }
public static BITTimer Create(float addTime = 1, UnityAction action = null)
{
BITTimer timer = new();
timer.excuteTime = Utility.Time.time + addTime;
timer.onExcute = action;
TimerSystem.queue.Enqueue(timer);
return timer;
}
public float excuteTime;
public bool isActive { get; internal set; }
public UnityAction onExcute;
public void Cancel()
{
isActive = false;
}
}
}
namespace BITKit.SubSystems
{
public class TimerSystem : SubBITSystem
{
internal static List<BITTimer> timers = new();
internal static ConcurrentQueue<BITTimer> queue = new();
public override void OnUpdate(float deltaTime)
{
List<BITTimer> nexts = new();
lock (timers)
{
timers.ForEach(x =>
{
if (x.excuteTime > Utility.Time.time)
{
if (x.onExcute is not null) x.onExcute();
x.isActive = false;
}
else
{
nexts.Add(x);
}
});
while (queue.TryDequeue(out var timer))
{
nexts.Add(timer);
}
timers = nexts;
}
}
}
}