GUI commands have to go inside the OnGUI function/method. However, you shouldn’t put any actual scripts inside OnGUI, because it will be called multiple times a frame.
What would you could do is something like this (this is in C#):
public Texture2D buttonTexture; // assign the texture in the Inspector panel
bool isPressed = false;
// Update is called once a frame (which can mean up to 60 times a second, depending on frame-rate)
void Update()
{
if (isPressed == true)
{
// add your extra code here
}
}
void OnGUI()
{
// this creates the RepeatButton in the centre of the screen. I think isPressed will remain true as long as it is pressed.
if(GUI.RepeatButton(new Rect(Screen.width / 2 - 50, Screen.height/2 - 50, 100, 100), buttonTexture) )
isPressed = true;
}
thanks Philip for your time but after pressing the GUI.RepeatButton, your isPressed statement always runs true. how will you make this false after releasing your GUI.RepeatButton?
I thought it would become false when the button was released - something I should probably check later. A quick work-around is to add a line into the OnGUI loop to reset isPressed to false afterwards, as follows:
void OnGUI()
{
if (GUI.RepeatButton(...) ) // leave the button details out for now
{
isPressed = true;
}
isPressed = false;
}
The problem is, that line will be called multiple times a second, so I’m hoping somebody comes along with something that’s more optimised.
I think this will always returns false since the last statement the OnGUI will read is the isPressed = false.
maybe this will do
void OnGUI()
{
isPressed = false;
if (GUI.RepeatButton(…) ) // leave the button details out for now
{
isPressed = true;
}
}
but the main problem is that the isPressed = false; is always read twice per frame, this will add another calculation in the game.
Why can’t they just not create a GUI.Button just like Input.GetMouseButtonUp?