Course contentsShow
← Unity Game Development
Lesson 113 of 8282. Scripting and LifecycleFree lesson

Detecting Raycast Hits on UI Elements

Learners will utilize the Graphic Raycaster to identify which specific UI elements are being targeted during user interaction events.

In this lesson, you will learn how to identify exactly which UI element a player clicks on by utilizing the GraphicRaycaster component.

Understanding the Graphic Raycaster

In Unity, UI elements like Buttons or Images aren't "seen" by the standard Physics raycasts we use for 3D objects. Instead, the UI system uses its own specialized tool called the Graphic Raycaster. When you click on your screen, this component shoots an invisible "ray" from your mouse position through the UI layers to see which elements reside at those coordinates.

To access this information in your code, we communicate with the EventSystem to process the click and identify the targets.

Implementation

To detect what is being hit, we need to provide the EventSystem with the current mouse position and a list to store the results of the raycast. Here is how you can set this up in a script:

using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections.Generic;

public class UIHitDetector : MonoBehaviour
{
    public GraphicRaycaster raycaster;
    public EventSystem eventSystem;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            // Set up the pointer event
            PointerEventData pointerData = new PointerEventData(eventSystem);
            pointerData.position = Input.mousePosition;

            // Create a list to store the hits
            List<RaycastResult> results = new List<RaycastResult>();

            // Raycast using the GraphicRaycaster
            raycaster.Raycast(pointerData, results);

            // Output the name of the first UI element hit
            foreach (RaycastResult result in results)
            {
                Debug.Log("You clicked on: " + result.gameObject.name);
            }
        }
    }
}

Why use a List?

You might notice we use a List<RaycastResult>. This is because UI elements can overlap. If you have a Button sitting on top of a Panel, the GraphicRaycaster will return both objects in the list, ordered from closest to furthest. By checking this list, you can determine if the user clicked the button, the background, or both, allowing for precise interaction logic.

Key Takeaway: The Graphic Raycaster works alongside the EventSystem to convert screen-space mouse clicks into a list of specific UI elements hit by the pointer.