- Home /
WaitForSeconds isnt working
Hey, I tried to use WaitForSeconds in my script, but its not working and i cant figure out whats the reason. Without the WaitForSeconds line in the coroutine everything is working fine. But as soon as i try to add this line its not working anymore.
public class Collision : MonoBehaviour
{
public GameObject gameover;
public GameObject explosion;
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Pylon")
{
Destroy(other.gameObject);
explosion.SetActive(true);
StartCoroutine(delay());
GameObject.FindGameObjectWithTag("Player").SetActive(false);
}
}
private IEnumerator delay()
{
yield return new WaitForSeconds(3);
gameover.SetActive(true);
Debug.Log("Game Over");
yield break;
}
}
Where is this script attached?
Remember that disabled gameObject can't run coroutines
what does not working anymore mean? This somewhat implies that there is some kind of error? if yes please share it.
If there is no error please elaborate what not working specifically means here.
Answer by GetLitGames · Apr 07 at 01:09 PM
Hellium's comment is most likely the answer. If your Collision script (the script shown) is on the Player's gameobject, it is being disabled and not continuing. These two lines: StartCoroutine(delay()); GameObject.FindGameObjectWithTag("Player").SetActive(false);
The coroutine will stop at your waitforseconds, and the next line executed is disabling the player gameobject, so if your Collision script is on the player, the coroutine is stopped because inactive gameobject do not run coroutines (they die as soon as gameobject becomes inactive)
If you want to get around the problem you can simply use Invoke("YourFunction", 3); and make a function to be called instead of using a coroutine.
If all you want to do is delay doing something, use Invoke - no need for a coroutine
Your answer
![](https://koobas.hobune.stream/wayback/20220613055037im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Yield WaitForSeconds Not Working. Coroutine. 1 Answer
yield return new WaitForSeconds () not working 1 Answer
How to get Coroutine's remaining time in WaitForSeconds? 2 Answers
How To Make UI Button 2 Appear Three Seconds After UI Button 1 is pressed 1 Answer
How to make WaitForSeconds work as a repeating/looping timer? 1 Answer