Referencing the documenation Unity - Scripting API: Physics.Raycast I’m having a problem getting Raycast to work the way I need.
I want to detect a hit ONLY when another object is between the Main camera and the target object (The gameObject with the following method attached)
void Update() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, 100)) print("Hit something!");
}
Can anyone help?
Make sure you want to raycast from your main camera and that your main camera has the tag “MainCamera”. Because you put “100” as the second argument in the raycast function, it will only check 100 units away from the camera.
If this does not help you solve your problem, let us know what your function is doing wrong, or if it seems to be doing nothing.
Also, you’d currently detect if you hit the object the script is on; I think you’re saying you want to check if the thing you hit is NOT the object that the script’s on, so you’d have to do this:
RaycastHit hit;
if(Physics.Raycast(ray, 100, out hit) && hit.transform != transform) print("Hit Something!");