问题
I am learning Unity with C# and studying the GUI Button. I found the following statement in Unity documentation:
"This means that your OnGUI implementation might be called several times per frame (one call per event). "
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void OnGUI() {
if (GUI.Button(new Rect(10, 10, 150, 100), "I am a button"))
print("You clicked the button!");
}
}
My questions are:
1) The above "if" statement will keep detecting the condition until it is true. It should be called polling input. Why does the above code use polling input instead of event driven input? (i.e. When someone press the button, the event is fired.). Although the if-statement will do nothing if the condition is false, it is keep detecting and not efficient compared with event driven input.
2) Why Unity use polling input in this case?
3) The above statement mention that "one call per event". Does it mean it is actually a event driven input, not polling input?
I am confusing about these questions and can't find the answer. Would someone explain to me. Thanks.
回答1:
1.If you press a Button GUI.Button
returns true
. If the Button is not pressed, GUI.Button
will return false
. It's as simple as that. That's not an event. It is simply a function that returns true or false depending on if the Button is pressed or not.
2.My guess is that Unity wanted to make things easier by doing this. Basically, you creating a Button and checking if it is pressed with just one line of code.
3
Does it mean it is actually a event driven input, not polling input?
It is still Polling but it is called only once when clicked until released. For GUI.Button
to be called, you must continuously call GUI.Button
in the OnGUI
function.
Forget about GUI.Button
at this time. What you are using now is called IMGUI.
You don't need it. There is a new UI system(uGUI). This is what you should be using and everything is based on event. Here is a tutorial for the new UI system. Ignore anything that requires the use of OnGUI
function.
Below is a simple way to register and unregister to the Button onClick
event.
public Button button;
Register Button Event
button.onClick.AddListener(() => yourCallBackFunction);
Un-Register Button Event
button.onClick.RemoveAllListeners();
You can find other UI event examples here.
来源:https://stackoverflow.com/questions/43289587/unity-gui-button-polling-input-vs-event-driven-input