syclamoth is right on the idea of moving your Input functionality to the Update function, but that doesn’t explain why the buttons don’t respond. In fact, the button in this code works just fine and prints “Works.” to my console:
if (GUI.Button(new Rect(Screen.width - 70, Screen.height - 70, 60, 60), "Towers") || Input.GetKey("b"))
{
Debug.Log("Works. ");
}
And indeed, why shouldn’t it? According to this article on MSDN, C# doesn’t even evaluate the second operant if the first turns out to be true, because in a logical-OR operation, the result is true if only one operant is true. So if the button is pressed, it makes no difference that there is also an Input condition in the if-sentence, because during the execution of that particular OnGUI, the above is semantically equivalent to:
if (GUI.Button(new Rect(Screen.width - 70, Screen.height - 70, 60, 60), "Towers"))
{
Debug.Log("Works. ");
}
Therefore, from the two snippets you’ve included alone, there is no explanation why your buttons don’t respond. If they don’t work at all, there must be something else in your script that interferes with them. Here is something else you may also want to consider about OnGUI: Unlike Update, it doesn’t execute once per frame. OnGUI executes as long as there are GUI-events to be processed, and this may be multiple times per frame, depending on what’s going on in the GUI system.
Try the following code in your OnGUI:
if (Input.GetKey("b"))
{
Debug.Log(Event.current.type);
}
if (GUI.Button(new Rect(Screen.width - 70, Screen.height - 70, 60, 60), "Towers"))
{
Debug.Log(Event.current.type);
}
This simply prints out the event type when you trigger some action. You’ll notice immediately that the first one, hitting b, will cause your Debug.Log to receive a whole bunch of GUI events, like Repaint, Layout, Keydown, Layout, Repaint, etc. etc. But the second one, pressing the button, prints out a single event type, named “used”. This doesn’t appear in any of the printouts caused by hitting the key, which demonstrates that hitting the b-key and hitting the button causes an unequal amount of GUI-events, which in turn causes your code to execute an uneven amount of times depending on which of the two conditions are met.
If you hit b, it keeps executing whatever you’re doing until you release it. Even if you use GetKeyDown instead of just GetKey, OnGUI executes 4 times on a single press, compared to just once with the button. So, in support of syclamoth’s answer, beware of using Input commands in OnGUI. They may execute more times than you think.