Search code examples
unity-game-engine2d-gamesraycastinggameobject

Unity click an object behind other using Raycast


There are many questions like this, but I didn't find a valid solution to my problem.

I would like to click an object behind a collider, this is my code:

    void Update () {
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out hit))
    {
        Debug.Log(hit.transform.name);
    }
}

I put this code inside the script attached to the first object but the debug log will never be called. Any ideas?


Solution

  • If I understand your question right, you want to click on the yellow sphere (see image) and want the name of the white cube?

    enter image description here

    There are two possible ways to do that:

    1. Ignore Raycast Layer

    You could give the yellow sphere the unity standard layer "Ignore Raycast":

    enter image description here

    Then your code should work (I added the on left mouse click)

        void Update()
    {
        if (Input.GetMouseButtonDown(0)) // Click on left mouse button
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    
            if (Physics.Raycast(ray, out hit))
            {
                Debug.Log(hit.transform.name);
            }
        }
    }
    

    2. Use Layer Mask

    See: Using Layers and Bitmask with Raycast in Unity

    If that's not what you're looking for please give further information and a screen shot of your problem.