Detect clicks and touches on GameObjects
Find out which GameObject the user clicks or touches, by casting a ray from the camera through the pointer position.
The Input System reports where the pointer is, but it doesn't know about the GameObjects in your scene. To find the GameObject under the pointer when the user presses, cast a ray from the camera through the pointer position. This approach works for mouse, pen, and touch input, because Pointer.current is whichever of these devices the user used most recently.
Prerequisites
Before you start, make sure that your scene meets the following requirements:
- The GameObjects that you want to detect have a Collider component. The example on this page uses 3D physics. For 2D GameObjects, use
Physics2Dinstead. - The scene has a camera tagged MainCamera, because the example uses
Camera.main.
Detect the GameObject under the pointer
To log the name of the GameObject that the user clicks or touches:
Create a C# script with the following code, and add it to a GameObject in your scene:
using UnityEngine; using UnityEngine.InputSystem; /// <summary> /// Example script that logs the name of the GameObject that the user clicks or touches. /// </summary> public class DetectClicksOnGameObjectsExample : MonoBehaviour { void Update() { // Pointer.current is the mouse, pen, or touchscreen that the user used most recently. var pointer = Pointer.current; if (pointer == null || !pointer.press.wasPressedThisFrame) return; // Cast a ray from the camera through the pointer position. var ray = Camera.main.ScreenPointToRay(pointer.position.ReadValue()); if (Physics.Raycast(ray, out var hit)) Debug.Log("Clicked " + hit.collider.gameObject.name); } }Enter Play mode, then click or touch a GameObject that has a Collider.
The Console window shows the name of the GameObject.
On a touchscreen, Pointer.current follows only the primary touch, which is the first finger the user puts down. While that finger stays down, the example ignores other fingers. To detect the GameObject under each finger, read every touch as described in Read all touches, and cast a ray from each touch position.
Detect clicks in other ways
Depending on your project, you can also use the following approaches:
- In Unity 6.4 and later,
MonoBehaviour.OnMouseDownand the otherOnMouseevents work with the Input System. - To use the Unity UI (uGUI) event system, add a Physics Raycaster component to your camera, and implement
IPointerClickHandlerin a script on the GameObject. Your scene also needs an EventSystem with an Input System UI Input Module.