detect click on canvas

Hello
I’m trying to add a HUD in my project and I want that when I click on the canvas ( which is 20% of the screen ) my player dont move.
It’s moving by a raycast statement, so I tryied this but it doesnt work :

        if (Physics.Raycast(ray, out hit) ) {
        
            if(hit.transform.gameObject.layer == 5)
            {
                print("Ui element was click");
            }
            SetDestination();
         }

There’s a fairly detailed example in the docs to do just this. I’ll clean their example up a bit for you, but the modifications for your exact situation are straightforward.

As mentioned on that page, this will be attached to your Canvas object so that it can access its GraphicRaycaster component.

using System.Collections.Generic;

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class CheckClicks : MonoBehaviour
{
    // Normal raycasts do not work on UI elements, they require a special kind
    GraphicRaycaster raycaster;

    void Awake()
    {
        // Get both of the components we need to do this
        this.raycaster = GetComponent<GraphicRaycaster>();
    }

    void Update()
    {
        //Check if the left Mouse button is clicked
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            //Set up the new Pointer Event
            PointerEventData pointerData = new PointerEventData(EventSystem.current);
            List<RaycastResult> results = new List<RaycastResult>();

            //Raycast using the Graphics Raycaster and mouse click position
            pointerData.position = Input.mousePosition;
            this.raycaster.Raycast(pointerData, results);

            //For every result returned, output the name of the GameObject on the Canvas hit by the Ray
            foreach (RaycastResult result in results)
            {
                Debug.Log("Hit " + result.gameObject.name);
            }
        }
    }
}