- Home /
How to start a timer after object is not active?
My code is not working. The timer only works when I removed the if statement on the start function there.
void Start()
{
if (uiPanel.activeInHierarchy == false)
{
StartCoroutine(Countdown());
}
}
IEnumerator Countdown()
{
while (countdownTime > 0)
{
countdownText.text = countdownTime.ToString();
yield return new WaitForSeconds(1f);
countdownTime--;
}
countdownText.gameObject.SetActive(false);
}
Answer by evskii · Nov 10, 2021 at 08:24 AM
If the timer is attached to the GameObject that is being disabled, the code is also being disabled, so the timer wont work as it is disabled. You have to have to have the timer be on a separate GameObject that isn't being disabled!
The timer and the GameObject that is being disabled is two different gameObject. @evskii
Ohh, I think I understand what is going on now.
You are telling the code to check if the uiPanel is active in Start, which only checks it at the very first frame, but you want to continuously check to see if it has been disabled, so what you can do is.
public bool timerStarted = false;
private void Update(){
if(uiPanel.activeInHierarchy == false && timerStarted == false){
StartCoroutine(Countdown());
timerStarted = false;
}
}
and then keep the rest of the code the same, except for when the Coroutine ends (just under where you set the countdownText to be inactive, add a line that saus timerStarted = true.
This way every frame you are checking to see if the panel has been disabled, and if it has and the timer hasn't already been started, then you can start the timer.
Another way you can do it is by using OnDisabled() on the object that is being disabled, but then you have to do some referencing, so the first method might be easier for you!
Your answer
![](https://koobas.hobune.stream/wayback/20220613045211im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Countdown Timer or WaitForSeconds? 2 Answers
How can I play a sound in sync with a countdown? 1 Answer
Time.timeScale problem 1 Answer
Toggle 2D Object Active? 0 Answers
Simple AI random roaming 2 Answers