How do you make a clock in Unity?
Many ways… Do you want a timer counting up, a timer counting down, an analog clock, a digital clock?
A reasonably simple timer counting up setup would be:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class SimpleClock : MonoBehaviour {
// set this in the editor
public Text clockDisplay;
int secondsPassed = 0;
// Use this for initialization
IEnumerator Start () {
while (true)
{
clockDisplay.text = secondsPassed.ToString();
yield return new WaitForSeconds(1);
secondsPassed++;
}
}
}
You can use system time
Or You can use a web service
Or if its a game world thing where you can initialize within the game here’s few tips
FixedUpdate()
is called in a fixed timestep (unlike Update()
)
you can set the fixed time step from Edit ==> Project Settings ==> Time Fixed Timestep value. (value is in seconds)
So you can use a int
variable inside a FixedUpdate()
and increment it in each update. and to get the time you can multiply with time step