public class TimeActioner
{
private float loadTime;
private float delayTime;
private float repeatTime;
private int totalRepeatCount = 1;
private int curRepeatCount = 0;
public int TimeAcId;
private System.Action<float> action;
public TimeActioner(int pId,float pLoadTime,float pDelayTime,System.Action<float> pAction,float pRepeatTime,int pRepeatCount = 1)
{
TimeAcId = pId;
loadTime = pLoadTime;
delayTime = pDelayTime;
repeatTime = pRepeatTime;
totalRepeatCount = pRepeatCount;
action = pAction;
}
public bool OnRuning(float pTime)
{
curRepeatCount++;
if(action != null)
action.Invoke(pTime);
return curRepeatCount >= totalRepeatCount && totalRepeatCount > 0;
}
public bool IsPass(float pTime)
{
if (curRepeatCount < totalRepeatCount)
{
if (pTime >= (delayTime + loadTime + curRepeatCount * repeatTime))
{
return true;
}
}
return false;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum TimeState
{
Runing = 1,
Pause = 2,
}
public class Timer:MonoBehaviour
{
public TimeState state = TimeState.Runing;
private Dictionary<int, TimeActioner> Timers = new Dictionary<int, TimeActioner>();
public float time;
public float Speed = 1;
private List<TimeActioner> passTimers = new List<TimeActioner>();
private List<int> endTimer = new List<int>();
private int acId = 0;
private void Update()
{
if (state == TimeState.Pause)
return;
OnRun(Time.deltaTime);
}
public int AddTimeActioner(float pDelayTime, System.Action<float> pAction, float pRepeatTime = 1, int pRepeatCount = 1)
{
acId++;
var timeActioner = new TimeActioner(acId,time,pDelayTime,pAction,pRepeatTime,pRepeatCount);
Timers.Add(acId, timeActioner);
return acId;
}
public void RemoveTimer(int pAcId)
{
if (Timers.ContainsKey(pAcId))
{
Timers.Remove(pAcId);
}
}
public void OnRun(float pDeltaTime)
{
time += pDeltaTime*Speed;
CheckTimer(time);
endTimer.Clear();
foreach (var temp in passTimers)
{
var isEnd = temp.OnRuning(time);
if (isEnd)
{
endTimer.Add(temp.TimeAcId);
}
}
foreach (var temp in endTimer)
{
RemoveTimer(temp);
}
}
public void CheckTimer(float pTime){
passTimers.Clear();
foreach (var temp in Timers)
{
if (temp.Value.IsPass(pTime))
{
passTimers.Add(temp.Value);
}
}
}
}