Created
November 18, 2021 22:13
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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