Search Unity

Showcase This is my "WTF is blocking UI clicks?" script that I use, hoping it helps some people

Discussion in 'UGUI & TextMesh Pro' started by Jinxology, Jun 7, 2023.

  1. Jinxology

    Jinxology

    Joined:
    Jul 13, 2013
    Posts:
    95
    After countless times over the years of running into the issue of "Why can't I click this button anymore!?", only to realize that a different element with raycastTarget on is blocking it, I created this very simple script. Just throw it on one GameObject in your scene (ie. GameController or something). Hopefully it will help some frustrated developers :)

    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3. using UnityEngine.EventSystems;
    4.  
    5. public class UIClickLister : MonoBehaviour
    6. {
    7.     public bool active;
    8.  
    9.     private void Update()
    10.     {
    11.         //List all the UI objects below mouse click that are set to receive raycasts (.raycastTarget == true)
    12.         if (active && Input.GetMouseButtonDown(0)) {
    13.  
    14.             PointerEventData eventData = new PointerEventData(EventSystem.current);
    15.             eventData.position = Input.mousePosition;
    16.             List<RaycastResult> results = new List<RaycastResult>();
    17.  
    18.             EventSystem.current.RaycastAll(eventData, results);
    19.  
    20.             if (results.Count > 0) {
    21.                 string objectsClicked = "";
    22.                 foreach (RaycastResult result in results) {
    23.                     objectsClicked += result.gameObject.name;
    24.  
    25.                     //If not the last element, add a comma
    26.                     if (result.gameObject != results[^1].gameObject) {
    27.                         objectsClicked += ", ";
    28.                     }
    29.                 }
    30.                 Debug.Log("Clicked on: " + objectsClicked);
    31.             }
    32.         }
    33.     }
    34. }
     
    karliss_coldwild likes this.