cant get my timer to countdown

Hi guys,

I am trying to get my timer to countdown. I have created a gui text object and called it txt_time and have attached the following code to it without any compiling errors but when i play the game its just stuck at 90 instead of decrementing can anyone help me out:

:slight_smile:

using UnityEngine;
using System.Collections;

public class CountdownTimer : MonoBehaviour 
{

	// the textfield to update the time to
	private GUIText textfield;
	
	// time variables
	public int allowedTime = 90;
	
	
		
	// Use this for initialization
	void Awake () 
	{
		textfield = GetComponent<GUIText>();
		
		UpdateTimerText();
		
		TimerTick();
	}
	
	 void UpdateTimerText()
	{
		textfield.text = allowedTime.ToString();
	
	}
	
	IEnumerator TimerTick()
	{
		// while there are seconds left
		while(allowedTime > 0)
		{
			// wait for 1 second
			yield return new WaitForSeconds(1);
			
			// reduce the time
			allowedTime--;
			
			UpdateTimerText();
		}
		
		// Gameover screen
		
	}
	
	
}

I believe you need to do StartCoroutine(TimerTick) because your TimerTick is an IENumerator.
More info here: Unity - Scripting API: MonoBehaviour.StartCoroutine

hi wolfhunter thansk for the reply,

would i have to write it like this you mean can you confirm :slight_smile:

IEnumerator StartCoroutine TimerTick()

    {
        // while there are seconds left
        while(allowedTime > 0)
        {
            // wait for 1 second
            yield return new WaitForSeconds(1);
           
            // reduce the time
            allowedTime--;
            
            UpdateTimerText();
        }
}

No, you need to call the method via StartCoroutine:

StartCoroutine(TimerTick());

Hi Glockenbeat,

So you mean write it without the IEnumerator and just have this as the function

StartCoroutine(TimerTick());

Could you show me what you mean by calling it just what that block of code looks like in my code so i get an idea what i should be doing, thanks again in advance

Hereโ€™s the same code with a comment applied:

using UnityEngine;
using System.Collections;
 
public class CountdownTimer : MonoBehaviour
{
 
	// the textfield to update the time to
	private GUIText textfield;
   
	// time variables
	public int allowedTime = 90;
   
   
	   
	// Use this for initialization
	void Awake ()
	{
		textfield = GetComponent<GUIText>();
	   
		UpdateTimerText();
	   
		StartCoroutine(TimerTick());	// <-- THIS is where the change to StartCoroutine happened
	}
   
	 void UpdateTimerText()
	{
		textfield.text = allowedTime.ToString();
   
	}
   
	IEnumerator TimerTick()
	{
		// while there are seconds left
		while(allowedTime > 0)
		{
			// wait for 1 second
			yield return new WaitForSeconds(1);
		   
			// reduce the time
			allowedTime--;
		   
			UpdateTimerText();
		}
	   
		// Gameover screen
	   
	}
   
   
}

Check out line 22.