I have a timer starting at 150 sec. When I extinguish the fire it updates to 600 sec.
After the update the timer in the script does stay on 600 sec.
What do I do wrong here?
Script 1 that refers to Script 2.
if (totalSec [0] == 2)
{
Destroy (FireFXFlameBall01);
}
if (totalSec [0] == 4)
{
Destroy (WhiteSmoke);
}
if (totalSec [0] == 6)
{
gameObject.GetComponent <TimerScript>().ChangeTimeLeft();
}
Script 2
public int timeLeft = 150;
public Text countdownText;
public GameObject TextGameOverTryAgain;
public GameObject FireFXFlameBall01;
public GameObject WhiteSmoke;
public bool timerChange = false;
public void ChangeTimeLeft ()
{
if (FireFXFlameBall01 == null && WhiteSmoke == null)
{
timerChange = true;
}
}
void Start ()
{
StartCoroutine ("LoseTime");
}
void Update ()
{
countdownText.text = ("Time to extinguish fire = " + timeLeft);
if (timeLeft <= 0)
{
StopCoroutine ("LoseTime");
countdownText.text = "Times Up!";
TextGameOverTryAgain.SetActive(true);
}
if (timerChange = true)
{
timeLeft = 600;
}
}
IEnumerator LoseTime()
{
while (true)
{
yield return new WaitForSeconds (1);
timeLeft--;
}
}
Short answer:
Set timerChange back to false right after you update the timeleft in line 39.
Some sidenotes/longer answer:
timerLeft is public, meaning that any script can change it directly. This doesn’t look like something you’re intending, as you have a method to change that, so I’d make it private. If you want to see it in Inspector, add [SerializeField] attribute to it.
The code to change timeLeft is in Update, so that gets checked every frame. Since you only want it to run every couple of minutes (as far as I can tell), move that completely to the ChangeTimeLeft method. This will also fix the original issue of it staying at 600 (it was updated every frame back to that value).
So your code could look like this:
[SerializeField]private int timeLeft = 150;
public Text countdownText;
public GameObject TextGameOverTryAgain;
public GameObject FireFXFlameBall01;
public GameObject WhiteSmoke;
//public bool timerChange = false; //timerChange no longer needed
public void ChangeTimeLeft ()
{
if (FireFXFlameBall01 == null && WhiteSmoke == null)
{
//timerChange = true; // timerChange no longer needed
timeLeft = 600;
}
}
void Start ()
{
StartCoroutine ("LoseTime");
}
void Update ()
{
countdownText.text = ("Time to extinguish fire = " + timeLeft);
if (timeLeft <= 0)
{
StopCoroutine ("LoseTime");
countdownText.text = "Times Up!";
TextGameOverTryAgain.SetActive(true);
}
}
IEnumerator LoseTime()
{
while (true)
{
yield return new WaitForSeconds (1);
timeLeft--;
}
}
One last sidenote is that your timer will not be exact 600 seconds. WaitForSeconds(1) will execute in the next game loop after 1 second has fully passed, you’ll have an accumulating error. This shouldn’t cause issues (I’d guess it’ll be in the range of single seconds), but something that’s good to know.