1

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?

Jr Antonio
  • 193
  • 1
  • 4
  • 20
  • This should work... Wait, hold on, are you using 2D physics objects? – Draco18s no longer trusts SE Aug 21 '18 at 00:48
  • As far as I know, this is only doable if your foreground object is on a separate layer that can then be ignored by the raycast. – Immersive Aug 21 '18 at 03:43
  • But why, why are you doing this? What type of object is behind the other object. It's likely that the answer to your questions is probably easy if we understand why you are doing this because might be another way to accomplish it. – Programmer Aug 21 '18 at 07:08
  • @Programmer I'm using a big sphere collider (with isTrigger activated) to see when an enemy enter in a particular zone, my problem was that is worked but when I tried to click the object I hit the collider (so my question was, how can I ignore the first collider?) anyway, xFL gived me a very great solution – Jr Antonio Aug 21 '18 at 09:15
  • @Draco18s just out of curiosity, why a 2d object could be a problem? – Jr Antonio Aug 21 '18 at 09:16
  • @JrAntonio It *could* be, as 2D physics objects do not respond to 3D raycasts. They're two entirely different physics systems and they don't interact. But I misread your question and you've got an answer. :) – Draco18s no longer trusts SE Aug 21 '18 at 14:21

1 Answers1

3

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.

xFL
  • 585
  • 10
  • 22
  • I implemented the first solution, it works without code, it just ignore my click on the first object. Thank you! – Jr Antonio Aug 21 '18 at 09:11