Unity - Gui 按钮问题 (Android)

Unity - Gui Button issues (Android)

我是 Unity 的新手,我正在为 android 创建我的第一个游戏,作为一个游戏。我有这个游戏,您可以通过按一个按钮来使用增强功能。玩家可以沿途获得多个提升。

此刻,我正在使用此代码来使用增强功能:

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

效果很好,除了我在 phone 上测试它时,我收集了 4 个提升,所有提升将一次性使用。

我也试过 GUI.Button 而不是 GUI.RepeatButton,但是如果我使用这个就没有任何效果。

是我做错了什么还是有更好的方法?

很正常,因为OnGUI每一帧都会被调用。您应该检查最后一个值是否为真,这意味着用户没有按下按钮,只是按住了它。试试这个:

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

希望我有所帮助!

我想通了我所有的提升都一次性使用的原因,我使用的是 RepeatButton 而不是 Button。虽然一开始这不起作用,但我将它与 (&& boosts > 0) 结合使用,现在它完美地工作了:)

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