This timer system I made and simply easy to use, if there are bugs or bad written code inform for the correct corrections.
how to use
active:
create a timer :
create a timer repeat:
C#:
using System;
using System.Collections.Generic;
using UnityEngine;
namespace TimerEdit
{
public class TimerEditStart {
//timer
private static GameObject LoadTime = new GameObject();
public static void Init() {
LoadTime.AddComponent<TimerEvento>();
UnityEngine.Object.DontDestroyOnLoad(LoadTime);
}
}
public class TimerEvento : MonoBehaviour
{
private static Dictionary<float, TimerAction> listTimers = new Dictionary<float, TimerAction>();
private static List<float> ListCleatTimer = new List<float>();
public float TimerAtual;
public float antiCrach = 0;
public static float timerSync = 0;
public class TimerAction {
public Action acao;
public int repeat;
public float time;
public TimerAction(float time_, int repeat_, Action acao_){
time = time_;
repeat = repeat_;
acao = acao_;
}
}
private void Update()
{
if (listTimers.Count > 0 && UnityEngine.Time.realtimeSinceStartup - antiCrach >= 1)
{
//antiCrach - Reduces the milliseconds update rate to seconds
antiCrach = UnityEngine.Time.realtimeSinceStartup;
ListCleatTimer.Clear();
//Validates the timer to activate
foreach (var checkTime in listTimers) {
if (checkTime.Key < UnityEngine.Time.realtimeSinceStartup) {
checkTime.Value.acao();
ListCleatTimer.Add(checkTime.Key);
}
}
// clear timers old's
foreach (var item in ListCleatTimer) {
if (listTimers[item].repeat == -1)
{
AntiExistente(listTimers[item]);
}
else if (listTimers[item].repeat > 0)
{
listTimers[item].repeat--;
AntiExistente(listTimers[item]);
}
listTimers.Remove(item);
}
}
}
//Responsible for adding the timers without repeating Key
public static void AntiExistente(TimerAction callback) {
timerSync = UnityEngine.Time.realtimeSinceStartup + callback.time;
if (listTimers.ContainsKey(timerSync))
{
callback.time += 0.05f;
AntiExistente(callback);
}
else {
//debug UnityEngine.Debug.Log("timer current: " + UnityEngine.Time.realtimeSinceStartup.ToString() + " timer event: " + timerSync.ToString());
listTimers.Add(timerSync, callback);
}
}
//Create timer dalay=seconds callback=action/function
public static void Once(float delay, Action callback) {
AntiExistente(new TimerAction(delay, 0, callback));
}
//Create timer with repetitions dalay=seconds reps=0(infinit) callback=action/function
public static void Repeat(float delay, int reps, Action callback) {
if (reps == 0) {
reps = -1;//infinit
}
AntiExistente(new TimerAction(delay, reps, callback));
}
}
}
active:
C#:
//active timer in your module
TimerEditStart.Init();
C#:
//Makes an Airdrop fall after 60 seconds
TimerEvento.Once(60f, () => {
ConsoleSystem.Run("airdrop.drop");
});
C#:
//It does an Airdrop drop after 60 seconds, activating the next automatic timer to drop another airdrop in 60 seconds infinitely.
TimerEvento.Repeat(60f, 0, () => {
ConsoleSystem.Run("airdrop.drop");
});