I am using JavaScript and I have a GUI button. When the button is held down a timer goes and when it is released the timer stops.
I’d like to have it so When the mouse releases the button the game would stop, show a game over and your time would be displayed.
I tried GetButtonUp function but that doesnt work with GUI.
Is there a way to make buttons without GUI ?
pragma strict
var counter: int = 0;
var Timer = 0.0;
var gameText: GUIText;
var btnStyle:GUIStyle;
var backGround:GUIStyle;
function Start(){
gameText = gameObject.GetComponent(GUIText);
}
function OnGUI () {
GUI.Box (Rect (100,100,200,300), "Hold IT", backGround);
if (GUI.RepeatButton(new Rect(50,50,100,110),"", btnStyle)) {
counter++;
Timer += Time.deltaTime;
var hours : int = Timer / 3600;
var minutes : int = Timer / 60;
var seconds : int = Timer % 60;
var fraction : int = (Timer * 100) % 100;
gameText.text = String.Format ("{0:00}:{1:00}:{2:00}:{3:00}", hours, minutes, seconds, fraction);
}
}
If I’m understanding your question correctly, I would do something like this:
var counter: int = 0;
var Timer = 0.0;
var gameText: GUIText;
var btnStyle:GUIStyle;
var backGround:GUIStyle;
//A bool to let us know if the button has been pressed or not
var down = false;
function Start(){
gameText = gameObject.GetComponent(GUIText);
}
function OnGUI () {
GUI.Box (Rect (100,100,200,300), "Hold IT", backGround);
if (GUI.RepeatButton(new Rect(50,50,100,110),"", btnStyle)) {
//when the button is pressed we make down equal true
down = true;
counter++;
Timer += Time.deltaTime;
var hours : int = Timer / 3600;
var minutes : int = Timer / 60;
var seconds : int = Timer % 60;
var fraction : int = (Timer * 100) % 100;
gameText.text = String.Format ("{0:00}:{1:00}:{2:00}:{3:00}", hours, minutes, seconds, fraction);
}
else if(down == true && Event.current.type == EventType.MouseUp) {
//An else if statement that will only be true if the button is not
//pressed but has been pressed in the past and the mouse has been lifted
//but to check in the OnGUI function if the mouse has lifted we need to use Event.current and
//check it against the event type of mouse up which will only be true if the mouse has been pressed down and released
//Thanks to BoredMormon for the Event.current == EventType.MouseUp part! This code wouldn't work without it!
//Game over code
//Remember to set down to false every time a new game is started or else
//the game over code will run right at the start of the game!
//Also remember that if you don't set down to false after the game over code every time you click the mouse and release the game over code will run
}
}
Here is some more info about Events:
Hope that helps! Let me know if it didn’t answer your question!