Performance: Button component and click events
This affects the responsiveness and smoothness of user interactions in the game or app.
Jump into concepts and practice - no test required
public void OnButtonClick() {
HandleClick();
}
// Assign OnButtonClick to the Button's OnClick event in the Inspectorvoid Update() {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit)) {
if (hit.collider.gameObject.name == "Button") {
HandleClick();
}
}
}
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual raycast in Update | N/A (GameObjects checked each frame) | N/A | High CPU usage for raycasts | [X] Bad |
| Unity Button OnClick event | N/A (Event-driven) | N/A | Minimal CPU usage | [OK] Good |
onClick property of a Unity Button component do?onClick property holds actions that execute when the button is clicked. Only "It lets you specify what happens when the button is clicked." correctly describes this; other options refer to disabling, color changes, or movement.onClick triggers actions on click [OK]onClick.AddListener with a lambda: button.onClick.AddListener(() => Debug.Log("Clicked!")). B uses invalid assignment (=), C calls wrong method Add(), D uses nonexistent Click.onClick.AddListener with lambda [OK]public Button myButton;
void Start() {
myButton.onClick.AddListener(() => Debug.Log("Button Pressed"));
}
What will happen when the button is clicked during play?Start() that executes Debug.Log("Button Pressed") on click, printing to Console. No errors, crashes, or visual changes occur.public Button myButton;
void Start() {
myButton.onClick = () => Debug.Log("Clicked");
}myButton.onClick fails because it is a UnityEvent requiring AddListener(). Other options misidentify unrelated issues like timing, syntax, or access modifiers.interactable = false using onClick.AddListener prevents further clicks. B uses invalid direct assignment. C references nonexistent gameObject.enabled (compile error). D calls nonexistent SetActive on Button (compile error).