- Home /
GUIButton only executes once
void OnGUI() {
if (GUI.Button(new Rect(Screen.width / 2, 0, Screen.width / 2, Screen.height), "")) {
transform.position += transform.forward * forwardSpeed * Time.deltaTime;
}
}
I want it to execute the line every frame while i hold the button.
But yet it only executes once when i press it and not multipe times.
You are using an I$$anonymous$$GUI (immediate mode graphical user interface) but expecting the button to maintain state - which it has no capacity to do. You could set a Boolean value to true when the button has been pressed, then set that Boolean to false once the user has released the mouse button
Answer by Bunny83 · Nov 10, 2014 at 04:27 PM
Uhm, simply use a RepeatButton instead.
Note: Since the Unity GUI is not made for multitouch input you can't press multiple RepeatButtons at the same time. The GUI system only has one active control at a time. You would have to roll your own solution using the Input.touches array and handle the input yourself.
huh, didn't know this existed. Awesome. Yeah this would be the best answer.
Answer by JazzWolf · Nov 09, 2014 at 08:31 PM
@Richyrich is right. OnGui runs once a frame and buttons can only be detected on the mouse up. What you can do is test to see if the mouse is down in the area of the button, turning a certain bool to true to run what you want repeatedly, then have the release of the button set the bool false. I think it'd look like this:
//creates a rectangle to test the click position and be used for the button
Rect rect = new Rect(Screen.width / 2, 0, Screen.width / 2, Screen.height);
//the hold boolean
public bool hold;
void OnGUI(){
Event e = Event.current;
//did mouse click within the rectangle of the button?
if ((e.type == EventType.MouseDown) && rect.Contains (Event.current.mousePosition)) {
hold= true; //initiate holding code
}
if (hold){
Debug.log("The button is held");
}
//if button is released, stop the hold code
if(GUI.Button(rect, " ")) {
hold = false;
}
}
Edit: I just tested the code. The object isn't moving so you gotta tweak your move code but i used a debug to confirm that holding the button continuously does something and releasing stops. Hope it helps!
FYI @JazWolf - most frame OnGUI() is run multiple times (not that it impacts your answer).
@JazzWolf - you have used the reserved keyword 'switch' as a variable name - that's not a ideal and may cause confusion.
yeah woops that didn't work I meant to come back and edit it after testing and i forgot to change the variable name at first.
Just one more switch (last line). I know you can do it ;)
Your answer
