Simple Timer

I am needing help geting started on creating a basic timer for my game I would like it to start with 60 seconds then count down to 0.

I know its problualy very basic but I have googled it and cant seem to find any for C#.

1 Like

Hi again


using UnityEngine;
using System.Collections;

public class SimpleTimer: MonoBehaviour {

public float targetTime = 60.0f;

Update(){

targetTime -= Time.deltaTime;

if (targetTime <= 0.0f)
{
   timerEnded();
}

}

void timerEnded()
{
   //do your stuff here.
}


}

Have fun.

If you want it to countdown, you could try something like this:

public class Countdown: MonoBehaviour {
    public int duration = 60;
    public int timeRemaining;
    public bool isCountingDown = false;

    public void Begin()
    {
        if (!isCountingDown) {
            isCountingDown = true;
            timeRemaining = duration;
            Invoke ( "_tick", 1f );
        }
    }

    private _tick() {
        timeRemaining--;
        if(timeRemaining > 0) {
            Invoke ( "_tick", 1f );
        } else {
            isCountingDown = false;
        }
    }
}

This will give you a public “timeRemaining” member that you can watch or display in another script. It also gives you a flag to watch to determine whether this object is actively counting down.

@GeorgeRigato

I am using the exact same code for my latest project, but it isn’t working. I am in Unity 5.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class PlayerMover : MonoBehaviour {

	public float speed;
	public Text countText;
	public Text winText;
	public float targetTime = 10.0f ;

	private Rigidbody rb;
	private int count;


	// Use this for initialization
	void Start () {
		rb = GetComponent<Rigidbody>();
		winText.text = "";
	}
	
	// Update is called once per frame
	void Update () {
	
		targetTime -= Time.deltaTime;

		if (targetTime <= 0.0f) {

			timerEnded();

		}


	}


	void OnTriggerEnter(Collider other) {
		
		
		
		if (other.gameObject.CompareTag ("Pick up")) {
			
			other.gameObject.SetActive (false);
			count = count + 1;
			SetCountText();

		}

		if (count >= 10) {

			winText.text="You won!";

			Application.Quit();

		}
	}


	void FixedUpdate() {
		
		float moveHorizontal = Input.GetAxis ("Horizontal");
		float moveVertical = Input.GetAxis ("Vertical");
		
		Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
		
		rb.AddForce(movement * speed);
	}

	void SetCountText (){
		
		countText.text = "Memories: " + count.ToString ();
		
	}

	void timerEnded (){

		winText.text = "You Lost!";

			Application.Quit();

	}

}

I have put the entire code just in case there is a problem somewhere else.