- Home /
Other
C# simple timer?
Hi,
I want to create a timer which will appear on screen when the player has collided in to a cube which at the moment brings up a pop up box displaying a question.
I would like to display a timer counting down from 10 to 0, with 0 destroying the pop up box and the player going back to the start.
At the moment if the player gets the question wrong, the player will go back to the start but has a long time to answer the question so would like to limit this with a timer. :)
I really can't think of a way to do this off the top of my head, so if anyone can either post some code or point me in the right direction, that would be awesome. :)
Answer by hahahaha · Apr 04, 2015 at 05:15 PM
Hey, I'd do it with a bool, and this simple Timer script.
public bool PopUpboxActive;
public float Timer = 10f;
void OnCollisionEnter(Collision col) {
//Keep whatever script you have here for Showing the popupbox but also add or incoporate the following...
PopUpboxActive = true;
}
void FixedUpdate() {
if(PopUpboxActive == true) {
Timer -= Time.deltaTime;
}
if(Timer <= 0f) {
PopUpboxActive = false;
Timer = 10f; //resets timer for next time;
//You can send the player back to the start here if you want
}
}
Void OnGUI() {
if (PopUpboxActive == true) {
GUI.Label (new Rect (100, 100, 400, 50), "Time Left to Answer Question" + Timer.ToString("F0")); //This will display the timer when the Popupbox is active, the "F0" part rounds the number to 0 decimal places, if you want to include decimals, change the number to 1 or 2 depending on how many decimal points :)
}
}
Hope this helps! :)
Sam
Answer by Veldars · Apr 04, 2015 at 03:37 PM
You can use a Text3D
private Text timerTxt;
void Start() {
// Get the text object in your scene
timerTxt = GameObject.FindGqmeObjectWithTag("Timer").GetComponent< Text >();
// Start the timer
StartCoroutine(StartTimer());
}
IEnumerator StartTimer(){
int timer = 10;
while (timer > 0) {
// Draw the resting time
timerTxt.Text = timer.ToString();
yield WaitForSeconds (1);
// Decrease the timer
timer--;
}
// You can call here your fail function...
PlayerFail();
}
Follow this Question
Related Questions
How to integrate timer into my C# script? 2 Answers
the countdown timer inside a spawn() and inside while loop not working 1 Answer
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Start timer on mouse0 click 1 Answer