GraphicRaycaster rc = GetComponent(); // get the GraphicRaycaster component PointerEventData pointerEvent = new PointerEventData(EventSystem.current); // create new event data pointerEvent.position = Input.mousePosition; // set the pointer position List results = new List (); // create new list for results rc.Raycast(pointerEvent, results); // perform the raycast if (results.Count > 0) { // do something with the UI element that was clicked on }
GraphicRaycaster rc = camera.GetComponentIn this example, we first get the GraphicRaycaster component attached to the camera and create a new ray using the camera position and forward vector. We then create a new PointerEventData object and an empty list for the results. We perform the raycast and if there are any results, we get the first object hit by the raycast and do something with it. Package library: The GraphicRaycaster Raycast method is part of the UnityEngine.UI package library in Unity.(); // get the GraphicRaycaster component attached to the camera Ray ray = new Ray(camera.transform.position, camera.transform.forward); // create a new ray using the camera position and forward vector PointerEventData pointerEvent = new PointerEventData(EventSystem.current); // create new event data List results = new List (); // create new list for results rc.Raycast(pointerEvent, results); // perform the raycast if (results.Count > 0) { GameObject selectedObject = results[0].gameObject; // get the first object hit by the raycast // do something with the selected object }