Tom
Tom

Reputation: 2472

Unity - Gui Button issues (Android)

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?

Upvotes: 2

Views: 651

Answers (2)

Tom
Tom

Reputation: 2472

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;
                } 
    }

Upvotes: 0

Chaoz
Chaoz

Reputation: 2260

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!

Upvotes: 2

Related Questions