Course contentsShow
← Unity Game Development
Lesson 194 of 8283. Physics and InteractionFree lesson

Implementing Precision Raycasting for Object Selection

Learn to detect specific game objects under the cursor using raycasts to enable interactable environmental elements.

In this lesson, you will learn how to bridge the gap between your mouse cursor and the 3D game world by using raycasting to select specific interactable objects.

The Concept of Screen-to-World Casting

When a player clicks their mouse, the game needs to translate a 2D coordinate on your screen into a 3D path into your scene. A Ray is essentially an invisible laser beam that originates from your camera and fires forward into the environment. If this beam strikes a collider belonging to an object, the physics engine can report back exactly what was hit.

To implement this, we use the Camera.main.ScreenPointToRay method, which takes your current mouse position (from your Input System) and converts it into a Ray object.

Implementing the Selection Logic

Once we have our ray, we use Physics.Raycast to probe the scene. Here is how you can detect if a player has clicked on a specific object:

void OnFire(InputValue value) // Triggered by your Input Action
{
    // Create a ray from the mouse position
    Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
    RaycastHit hit;

    // Check if the ray strikes an object within 100 meters
    if (Physics.Raycast(ray, out hit, 100f))
    {
        // Access the object that was hit
        GameObject selectedObject = hit.collider.gameObject;
        Debug.Log("You selected: " + selectedObject.name);
    }
}

Refining the Interaction

To ensure you only interact with objects that are meant to be picked up or activated, it is best practice to use Layers. By assigning your interactable items to a specific "Interactable" layer, you can pass a LayerMask to Physics.Raycast. This prevents the ray from accidentally selecting walls, floors, or other decorative props that don't need to respond to the player. By filtering the raycast, you keep your interaction system clean, performant, and bug-free.

Key Takeaway: By converting screen coordinates into a physics Ray, you can precisely identify and interact with specific objects in your 3D environment based on user input.