sorry for my english, i have 1 button i need to chick if it is being pressed or held down how do i do this
1 Answer
1You can use Input.GetButton(“buttonName”): this function returns true while the button is pressed. There are equivalents for keys (Input.GetKey(“a”), for instance) and for GUI ( GUI.RepeatButton)
EDITED: Well, doing what you want with GUI buttons is more complicated than I supposed: contrary to what I thought, RepeatButton doesn’t return true while pressed - it actually returns true and false alternately each OnGUI! This complicates things, because there’s no steady state to rely on.
But the show can go on: since Unity doesn’t return a steady state for us, let’s create our own! We can use a boolean flag, speedButton, which will be set when RepeatButton returns true and reset when the mouse button is released.
To simplify things a little, let’s check the time only when RepeatButton is released: if it’s greater than the limit, select high speed, otherwise select low speed:
var speed: float;
var timeThreshold: float = 0.6; // 600mS to select high speed
private var speedButton = false; // current button state
private var lastState = false; // last button state
private var speedTime: float = 0; // time measurement
function OnGUI(){
// create a steady state result for RepeatButton:
// set speedButton when RepeatButton is true...
if (GUI.RepeatButton(Rect(10,10,200,100), "Speed")){
speedButton = true;
}
// and reset it when mouse button released:
speedButton &= Input.GetMouseButton(0);
// now speedButton can be verified:
if (speedButton != lastState){ // if button changed state...
lastState = speedButton; // register current state
if (speedButton){
// if button down define the threshold time
speedTime = Time.time + timeThreshold;
} else {
// if button up select speed according to time elapsed
speed = (Time.time > speedTime)? 10 : 5;
}
}
}
sorry it didnt work i replaced the speed =5 with print(low speed) and when i turn the game one the low speed is always there even with out pressing the button. my programming skills arnt good so i dont know how to fix it
– anon27772772Dear God! RepeatButton actually returns true and false alternately while pressed, what invalidates my previous algorithm! To solve this, I edited my answer and added a boolean flag that is true while the RepeatButton is pressed and becomes false when it's released - take a look at my answer.
– aldonaletto
By button, do you mean keyboard, mouse or GUI? And please read the manual, because your answer is there (for any of the case above).
– Kryptosits gui, when i read the script reference it talked about the button and the GUI.RepeatButton but they are separate i want them to be the same button
– anon27772772