0
0
Unityframework~8 mins

Button component and click events in Unity - Performance & Optimization

Choose your learning style9 modes available
Performance: Button component and click events
MEDIUM IMPACT
This affects the responsiveness and smoothness of user interactions in the game or app.
Handling button clicks in Unity UI
Unity
public void OnButtonClick() {
  HandleClick();
}
// Assign OnButtonClick to the Button's OnClick event in the Inspector
Uses Unity's built-in event system to handle clicks only when they happen, reducing overhead.
📈 Performance GainSingle event call per click, improving input responsiveness
Handling button clicks in Unity UI
Unity
void 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();
      }
    }
  }
}
Checking for clicks every frame and using raycasts is expensive and can cause input lag.
📉 Performance CostTriggers multiple raycasts per frame, blocking input responsiveness
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Manual raycast in UpdateN/A (GameObjects checked each frame)N/AHigh CPU usage for raycasts[X] Bad
Unity Button OnClick eventN/A (Event-driven)N/AMinimal CPU usage[OK] Good
Rendering Pipeline
Button click events are processed by Unity's event system which listens for input and triggers callbacks without continuous polling.
Input Processing
Event Dispatch
UI Update
⚠️ BottleneckInput Processing when using manual polling and raycasts
Core Web Vital Affected
INP
This affects the responsiveness and smoothness of user interactions in the game or app.
Optimization Tips
1Avoid checking for clicks every frame with raycasts.
2Use Unity UI Button's OnClick event for efficient click handling.
3Profile input handling to detect unnecessary CPU usage.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with checking button clicks using raycasts every frame in Update?
AIt causes unnecessary CPU usage by running raycasts even when no clicks happen.
BIt improves responsiveness by checking clicks constantly.
CIt reduces memory usage by avoiding events.
DIt prevents UI from rendering.
DevTools: Unity Profiler
How to check: Open Profiler, record while clicking button, check CPU usage and Event system calls.
What to look for: Look for high CPU spikes during Update or excessive raycast calls indicating inefficient input handling.