Je vous fait profiter d'un petit script que j'ai fait et que j'utilise, une sorte de gestion de timer pour par exemple faire des choses toutes les x secondes...
Exemple d'utilisation de mon script :
Code : Tout sélectionner
void Awake () {
// Initialisation du timer
TimeScript.addTimer ("IdentifiantTimer", 4);
}
void Update () {
if (TimeScript.isTimerReady ("IdentifiantTimer")) {
// Ici le code est execute toutes les 4 secondes :)
}
}
Code du fichier TimeScript :
Code : Tout sélectionner
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TimeScript : MonoBehaviour {
private class InfoTimer {
public int nbSecondes;
public float saveLastTime = 0f;
}
private static Dictionary<string, InfoTimer> dicTimer = new Dictionary<string, InfoTimer>();
public static void addTimer(string name, int nbSecondes) {
InfoTimer infoTimer = new InfoTimer ();
infoTimer.nbSecondes = nbSecondes;
infoTimer.saveLastTime = Time.time + infoTimer.nbSecondes;
dicTimer.Add (name, infoTimer);
}
public static void resetTimer(string name) {
InfoTimer infoTimer;
if (dicTimer.TryGetValue (name, out infoTimer)) {
infoTimer.saveLastTime = Time.time + infoTimer.nbSecondes;
}
}
public static void changeTimer(string name, int nbSecondes) {
InfoTimer infoTimer;
if (dicTimer.TryGetValue (name, out infoTimer)) {
infoTimer.nbSecondes = nbSecondes;
infoTimer.saveLastTime = Time.time + infoTimer.nbSecondes;
}
}
public static bool isTimerReady(string name) {
return isTimerReady(name, true);
}
public static bool isTimerReady(string name, bool resetTimer) {
InfoTimer infoTimer;
if (dicTimer.TryGetValue (name, out infoTimer)) {
if (Time.time > infoTimer.saveLastTime) {
if(resetTimer) {
infoTimer.saveLastTime = Time.time + infoTimer.nbSecondes;
}
return true;
}
}
return false;
}
}