Search code examples
unity-game-engineraycastinggameobject

Does Raycast only work when the script is on main camera?


I want to get the raycast work as a mouse (or Touch) from main camera, and when click, and hit on an object then it will trigger something. I have the script in the Object's update() as below:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);   
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
  // Debug output to confirm it is hit. 
}

It is pretty standard script that I see from many tutorials. However, it doesn't hit the Debug line.

The only different is that it is the object's update, not on the main Camera's script update(). Does it make the difference?

should the code in the update script belong to the original game object( or camera) shooting out the ray? or can it be in any game object's attached script's update()?

The object I have do not have any collider, do I need one on the object in order to have the ray collide it?


Solution

  • With Physics.Raycast you can shoot a ray from what ever point in the space into any direction. It doesn't matter at all in which gameObject the script is attached to as long as you are able to calculate the starting point and direction somehow.

    The problem is that you don't have colliders on your ray targets. Raycasting is only calculating what collider the ray is hitting.

    So adding colliders will fix your problem. Just remember that if you use 2D colliders from Physics2D tab, you need to use Physics2d.Raycast. And if you use 3D colliders from Physics tab, you need to use Physics.Raycast.