In a game I’m making I want to have a countdown timer that starts at 1:00 and goes down to 0:00. I want the timer to be displayed in some text that I have placed down. I have tried for a long time to get this to work but it just won’t. Please help me.
2 Answers
2Simple as this:
// Remember using using UnityEngine.UI;
public Text text; // set it to your timer text on GUI
float tim = 60;
void Update()
{
text.text = (Mathf.Floor(tim/(60*60)))+":"+(Mathf.Floor(tim/60)%60)+":"+Mathf.Floor(tim%60);
tim -= Time.deltaTime;
}
Explanation:
1st thing in “text =” is hour counter, next is minute counter modulo 60 so it will display 0-59 minutes and not more because that goes to hour section. Next is seconds modulo 60 because 60 seconds is minute so it displays 0-59 seconds on it.
just in case you dont know what modulo is:
it’s symbol is “%” and it returns rest from division, so 20%21 = 20 and 21%21 = 0 22%21 = 1 and so on. just loop of numbers with given lenght.
I agree it's not ideal. For my purposes I think it works however if possible I'd love to optimise it in the future. For reference the texture I generate is about 85Mb (4096x4096), which is pretty big but as I'm using it as the texture for the terrain, it'll be the biggest texture in the game anyway and it'll only be generated once.
– Alistair401private float timeInSeconds = 60;
void Update() {
float minutes = Mathf.FloorToInt (timeInSeconds / 60);
float seconds = Mathf.FloorToInt (timeInSeconds) % 60;
Debug.Log (string.Format("{0}:{1}", minutes.ToString("0"), seconds.ToString("00")));
timeInSeconds -= Time.deltaTime;
}
Why not just create the vertex and triangle array correctly the first time? If you generate the mesh procedurally anyway, it sohuld be trivial to change the code. In fact, not having to share vertices between quads or triangles is much easier.
– Cherno