I was hoping someone could lend their advice, I’m relatively new to coding and would appreciate the input. I was combing the forum and found a countdown script that works quite well when applied to a 3d text. I was just wondering how to expand it in the following ways:
At 0 seconds, it should stop the timer and display a message
At fixed intervals (arbitrary) it can prompt a message
The script is the following:
using UnityEngine;
using System.Collections;
public class Timer : MonoBehaviour {
public float time = 20.0f; // Arbitrary number
TextMesh tm;
void Update () {
time -= Time.deltaTime;
if(time > 0){
//If time is greater than 0, display time left
tm.text = Mathf.RoundToInt(time).ToString();
}else{
//Otherwise display this
tm.text = "Time is up!";
}
}
As an aside, do you have any advice for delaying the countdown until prompted to begin again? Another script will be responsible for triggering this. Again, thanks in advance!
bool paused = false;
void ToggleTimer(){
paused = !paused;
}
void Update () {
if(!paused){
//If not paused
if(time > 0){
//If time is greater than 0, display time left and reduce time
time -= Time.deltaTime;
tm.text = Mathf.RoundToInt(time).ToString();
}else{
//Otherwise display this
tm.text = "Time is up!";
}
}else{
//If paused, don't reduce time and display a paused message
tm.text = "Timer paused";
}
}
You would have to use some way to run the ToggleTimer(); function, maybe pressing a certain key? For R for example:
One side note: Rather than using Mathf.RoundToInt, I recommend learning to use string.Format, ToString(string), and string formatting codes in general - this is exactly what they’re made for, they’re usually more efficient, and you’ll get a lot more versatility.
Well whenever I press R while previewing, nothing happens, it just keeps counting down. As for the GetKeyDown if statement, is this where I would reference the other script that triggers either the countdown or pause?