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?
If I understand your question right, you want to click on the yellow sphere (see image) and want the name of the white cube?
There are two possible ways to do that:
1. Ignore Raycast Layer
You could give the yellow sphere the unity standard layer "Ignore Raycast":
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.