Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created November 18, 2021 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisryosuke/8821a61797dc39f98294bef3aaa167c5 to your computer and use it in GitHub Desktop.
Save whoisryosuke/8821a61797dc39f98294bef3aaa167c5 to your computer and use it in GitHub Desktop.
Unity - Detect click on canvas using graphic raycaster -- via: http://answers.unity.com/answers/1526703/view.html
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);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment