- Home /
Invoke is not working consistently
I have a problem with this script. What it is supposed to do, is when the timer (timeLeft) = 0, it is supposed to change the text (countdownText) to "Rush!", then after 15 seconds, change the timer to 11 seconds. It works flawlessly the first time through, but then, once 11 seconds have passed after the first time, it doesn't show "Rush". Instead it goes straight back to 11 seconds, and counts down from there again. Does anyone know why this is? Here is the code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Countdown : MonoBehaviour {
public float timeLeft = 60;
public AudioClip rushIncomingClip;
public Spawner spawner;
public float maxSpawnDelaySetter = 4f;
private Text countdownText;
private Color textColor;
private Color defaultTextColor;
private AudioSource source;
private bool bellNotRung = true;
private bool timerHasBeenReset = false;
// Use this for initialization
void Start () {
countdownText = GetComponent<Text>();
defaultTextColor = countdownText.color;
source = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
countdownText.text = Mathf.RoundToInt(timeLeft).ToString();
countdownText.color = textColor;
timeLeft -= Time.deltaTime;
if (timeLeft <= 10.49) {
textColor = Color.red;
} else {
textColor = defaultTextColor;
}
if (timeLeft < 0) {
if (bellNotRung) {
source.PlayOneShot(rushIncomingClip, 1f);
bellNotRung = false;
}
countdownText.text = "Rush!";
Rush();
timerHasBeenReset = false;
Invoke("TimerReset", 15f);
}
}
void TimerReset() {
if (timerHasBeenReset == false) {
timeLeft = 11f;
timerHasBeenReset = true;
}
bellNotRung = true;
maxSpawnDelaySetter = 4f;
}
void Rush() {
maxSpawnDelaySetter = 0.6f;
}
}
Once timer reaches any value < 0 it will be constantly calling Invoke, since it takes 15s until it resets to any value greater than 0 again, not sure if this will solve your problem, but it's a problem let's start there.
Your answer
![](https://koobas.hobune.stream/wayback/20220612083928im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Make sure levels assets are loaded before switching? 1 Answer
Unity5 build issue, not showing texture. 1 Answer
2D Platformer Bug 0 Answers