- Home /
Stop Watch start when told
I am making a game in which case there is a stop watch that keeps on counting up (in seconds) when the player hits the "E" key. But I am having trouble. Depending on how long the player takes, it will start the stop watch at however long he takes.
Example: If the player takes 10 seconds before pressing E to start the timer, the timer will start at 10 and continue to count up from there
Here is what my code looks like:
var survivalTime = 0; var subsurtimel = 0; var starttime; var didStartTime = false; var acsurvivaltime = 0;
function Start(){
subsurtimel = Time.time;
}
function OnGUI(){
GUI.Label(Rect( 250,150, 200, 30), "Survival Time: " + acsurvivaltime);
}
function Update () {
acsurvivaltime = subsurtimel;
if(PlayRocketAnimation.canlaunch){ //if the user hits the E key
if(!didStartTime){
survivalTime = (Time.time - subsurtimel) + 1 ;
}
} }
Please format and code your questions please by highlighting the code and pushing the 10101 button up top. Thanks!
Answer by Justin Warner · Apr 19, 2011 at 04:31 PM
Alright, to get input: http://unity3d.com/support/documentation/ScriptReference/Input.html
To get the time in seconds: http://unity3d.com/support/documentation/ScriptReference/Time.html
So, get the start time, get the time they push the button, get the difference between, and then the add that to the time they push the button, and thats the new time they have for the timer to go up...
So put the Input in the update function, and then use the times as I explained above. Pretty easy...
Is their a specific question you have? You don't really specify one.
Answer by Statement · Apr 19, 2011 at 04:41 PM
How about just incrementing a timer from the moment the user pressed E?
var timer : float = 0;
// Wait until E is pressed, and canlaunch is true. while (!(PlayRocketAnimation.canlaunch && Input.GetKeyDown(KeyCode.E))) { yield; }
// Then go into a loop where you increase the timer every frame. // Alternatively you can set some condition when to stop the timer. while (true) { timer += Time.deltaTime; yield; }
function OnGUI() {
var msg = String.Format("Survival Time: {0}", Mathf.FloorToInt(timer)); GUI.Label(Rect(250,150, 200, 30), msg);
}