- Home /
Making a timer
Hi there i made a simple timer calculating the time im playing.
How can I change my seconds to minutes when it reaches 60 secs.
How can I kill my avatar when my timer reaches 5 min.
Here is what I did so far.
using UnityEngine; using System.Collections;
public class AvatarTimer : MonoBehaviour
{
public GUIText timer;
public float myTimer = 0.0f;
void Update ()
{
myTimer+=Time.deltaTime;
timer.text = "Time :" + (int)myTimer;
if (myTimer >= 300.0f)
{
Debug.Log("GAME OVER");
}
}
}
THX
how would I change timer.text = "Time :" + (int)myTimer;
to JavaScript I already did the rest.
Answer by JinxM · Feb 28, 2012 at 11:16 PM
So it looks like the Debug.Log line should work correctly, right? Add in the same position a Destroy() function with a reference to your Avatar GameObject and it should work.
e.g. if the AvatarTimer script is on the Avatar GameObject:
if (myTimer >= 300.0f)
{
Debug.Log("GAME OVER");
Destroy(gameObject);
}
Changing seconds to minutes is slightly more complicated and requires some formatting with ToString():
int minutes = (int)myTimer / 60;
int seconds = (int)myTimer % 60;
timer.text = "Time: " + minutes.ToString() + ":" + seconds.ToString("00");
Alternately, there's some wacky stuff you can do with System.DateTime and System.TimeSpan to format it automatically instead of dividing and modding by 60, but this is a little easier to understand.
Your answer
Follow this Question
Related Questions
How to stop a Countdown Timer? 1 Answer
making a timer (00:00) minutes and seconds 10 Answers
Countdown Timer Help About putting 0's 1 Answer