- Home /
gameTimer needs to be based on an event, not onGUI
Hi - I have a timer function set up which I programmed based on some posting here, but it is set up to run through the onGUI event, so the time is based on the amount of time the game has been running (I guess). But what I want it to do is not start the timer til the user clicks the logo to begin play. The way I have it set up now, if the user takes 10 seconds to click the start button, and the game timer is set to count down from 60 seconds, by the time they begin play there will only be 50 seconds left in the game. How do I change this to trigger after the click?
Here's my code:
TIMER SCRIPT:
private var startTime = 60;
var textTime : String; //added this member variable here so we can access it through other scripts
var beginPlay : boolean = false;
var guiTime : int;
function OnGUI () {
if (beginPlay == true){
guiTime = startTime - Time.time; //how to count down
var timeText = guiTime.ToString();
if (guiTime < 0){
//END GAME
} else {
timerTextRef.text = timeText;
textTime = timeText;
}
}
}
MENU SCRIPT:
var cameraRef : GameObject;
function Update () {
if (Input.touchCount > 0 ) {
for(var i : int = 0; i< Input.touchCount;i++) {
var touch : Touch = Input.GetTouch(i);
if ( touch.phase == TouchPhase.Began && guiTexture.HitTest(touch.position)) {
guiTexture.enabled = false;
cameraRef.GetComponent(Timer).beginPlay = true;
}
}
}
}
Answer by heaversm · Jul 28, 2011 at 06:32 PM
I ended up doing this. I'm sure someone will inform me that this is the wrong way to do timers, but it worked for my purposes:
function Start(){
startTime = 10;
timeDown();
}
function timeDown(){
yield WaitForSeconds (1);
startTime--;
repeatTime();
}
function repeatTime(){
if (startTime < 1){
endGame();
} else {
timeDown();
}
}
Answer by DaveA · Jul 28, 2011 at 05:03 PM
You need to set startTime when the touch is detected, not on start (by assigning it statically), so put startTime = 60 after, say , guiTexture.enabled = false;
If I do that, the countdown (Time.time in onGUI) is still being based off of the total game time, and I also get an error in onGUI that startTime does not refer to anything because it hasn't been instantiated yet. What I need to figure out is how to make this not based on onGUI, right?
Your answer
Follow this Question
Related Questions
if statement will only execute once 1 Answer
"Escape" not working to open menu? 1 Answer
Best way to display a (highscore) dialogue 0 Answers
Shift from one scene to another (based on time) 1 Answer
Alternate solution to onGUI for GUI? 4 Answers