Thursday, December 4, 2014

Unity: Implement a Timer

This post shows how to create a timer in Unity similar to the one used in WinForms or WPF. To create a timer in a Unity game, create a C# script and attached to a empty game object, The content of the C# looks like the following:

using UnityEngine;
using System.Collections;

public class Timer : MonoBehaviour {
 public float timerInterval=1.0f; //timer interval in seconds

 // Call this when the scene is loaded before the Start()
 private void Awake()
 {
  StartCoroutine (TimerCoroutine ());
 }

 private IEnumerator TimerCoroutine()
 {
  while(true)
  {
   Timer_OnTicked();
   yield return new WaitForSeconds(timerInterval);
  }
 }

 private void Timer_OnTicked()
 {
  //TODO: put your implementation here
 }

 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }
}

As can be seen above, the implementation starts the timer when the Unity scene containing the game object is loaded (i.e. in the Awake() method), this is done via the StartCoroutine() method which starts the co routine TimerCoroutine(). The TimerCoroutine() contains an infinite loop which updates based on the timerInterval. The actual update is to be implemented inside the Timer_OnTicked() handler.

No comments:

Post a Comment