Unity - Gui Button issues (Android)

632 views Asked by At

I'm fairly new to Unity and I am creating my first game for android as a bit of a play around. I have this game where you can use a boost by pressing a button. The player can pick up multiple boosts along the way.

At the minute, I am using this code to use a boost:

public void OnGUI()
     {
         if (GUI.RepeatButton(new Rect(20, Screen.height - 150, Screen.width/10, Screen.width/10), boostButtonIcon))
         {
             pressedButton = true;
             //do boost stuff

         }
         else
         {
             pressedButton = false;
         }
     }

Which works fine, except when I test it on my phone, and I collect say, 4 boosts, all the boosts will be used in one go.

I also tried GUI.Button instead of GUI.RepeatButton, but if I use this nothing works.

Am I doing something wrong or is there a better way?

2

There are 2 answers

0
Tom On BEST ANSWER

I figured out the reason all my boosts got used in one go, I was using RepeatButton instead of Button. Although this didn't work at first I combined it with (&& boosts > 0) and it now works perfectly :)

    public void OnGUI() 
    {
                if (GUI.Button(new Rect(20, Screen.height - 150, Screen.width/10, Screen.width/10), boostButtonIcon) && boosts > 0)
                {
                    useBoostSound.Play();   
                    rigidbody.AddForce(boostVelocity, ForceMode.VelocityChange);    
                    boosts -=1;
                } 
    }
4
Chaoz On

It's very normal, as OnGUI will be called every frame. You should check if the last value is true, which means the user hasn't pressed the button, only held it. Try this:

if (GUI.RepeatButton(new Rect(20, Screen.height - 150, Screen.width/10, Screen.width/10), boostButtonIcon))
{
     if (!pressedButton)
     {
         //do boost stuff
     }
     else pressedButton = true;
}

Hope I helped!