1
\$\begingroup\$

In my game I've got a timer script, which counts down unless the game is paused, but whenever the variable for pausing is true, something in the timer script makes the editor itself crash, and I have to pull out the task manager to close unity because it freezes up completely.

Timer.cs

using UnityEngine;
using System.Collections;

public class Timer : MonoBehaviour {

  public LevelManager levelManager;

  // Use this for initialization
  void Start () {
    levelManager = FindObjectOfType<LevelManager>();
    StartCoroutine ("timerUpdate");
  }

  // Update is called once per frame
  void Update () {
  }

  IEnumerator timerUpdate (){
    while (levelManager.levelTimeSeconds>0) {
      if (levelManager.isPause== false){
        yield return new WaitForSeconds(1);
        levelManager.levelTimeSeconds -= 1;
      }
    }
    levelManager.isOver = true;
  }
}

Anyone have any idea what's causing the editor to crash once isPause is true?

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

when it becomes true your loop will run forever :) Better use:

while (levelManager.levelTimeSeconds>0 && levelManager.isPause== false)
{
        yield return new WaitForSeconds(1);
        levelManager.levelTimeSeconds -= 1;
}
\$\endgroup\$
0
-1
\$\begingroup\$

While loops must be used WITH CAUTION. A lot of times if while is not used in a correct manner it will always be true. Infinite loops can cause a program to crash, freeze or hang, like you experienced.

If dealing with arrays, use foreach instead if possible.

In case you're new to foreach syntax:

foreach (type elementname in variablename) { /*code here*/ }
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .