- Home /
Countdown Timer
I am trying to make a game where you have 3 seconds to shoot a moving alien that keeps respawning. I want it to be that when I shoot it it sets the time back to 3 seconds so I have 3 seconds to try and shoot it again and e.t.c until I dont manage to shoot it in 3 seconds and I lose. I have everything in place except the timer script that I want to countdown showing seconds and milliseconds. Could you please try to make this script countdown from a number instead of up from 0?
using UnityEngine; using UnityEngine.UI; using TMPro;
public class Timer : MonoBehaviour { public TextMeshProUGUI timerText; public bool playing; public float timer;
void Update()
{
if (playing == true)
{
timer += Time.deltaTime;
UpdateText(timer, timerText);
}
}
void UpdateText(float t, TextMeshProUGUI text)
{
int seconds =- Mathf.FloorToInt(t % 60f);
int milliseconds =- Mathf.FloorToInt((t * 100f) % 100f);
text.text = seconds.ToString("00") + "." + milliseconds.ToString("0");
}
}
Answer by Duckocide · Oct 27, 2020 at 03:08 PM
I'd use a coroutine for this. Have a property (boolean) to indicate if times up or not. Every time you want to start the 3 second timer, call the public method "StartTimer" - It will safely stop and start a new timer. In your Update method, monitor the timesUp property ... If it goes true, time is up!
public bool timesUp = false;
public void StartTimer()
{
StopCoroutine(StopWatchCR());
StartCoroutine(StopWatchCR());
}
private IEnumerator StopWatchCR()
{
timesUp = false;
yield return new WaitForSeconds(3);
timesUp = true;
}
Its fine Duckocide I just spent the whole day trying to figure this out until i realised i dont need the whole complicated mess of milliseconds and seconds. I literally just need to say the timer is -= to time.deltatime and then put "0.00" into the .ToString() brackets.
No worries. Just so you know, A coroutine is a great way to do something in parallel to the core unity lifecycle of Update(), FixedUpdate(), LateUpdate() etc... They can often improve performance as your not slowing Unity down.
Answer by johnburkert · Oct 27, 2020 at 05:16 PM
You can replace the mess inside of UpdateText with a call to ToString
timerText.text = timer.ToString("F"))
https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings