I have experience with Unity, but I can’t explain this. Any help would be appreciated.
I would like to detect things under the cursor, so I was using Physics.Raycast, but I noticed that sometimes it does not hit some objects. I was trying to come up with a minimal case which leads to the problem, here it is:
This is the code doing the raycast for testing purposes:
void OnValidate()
{
if ( castRay )
{
castRay = false;
if ( Physics.Raycast( new Vector3( 3.5f, 12, 21 ), new Vector3( 0, -1, 0 ), out RaycastHit result ) )
Debug.Log( $"hit: {result.collider} at {result.distance}" );
else
Debug.Log( "No hit" );
}
}
I added this as a member function to an object being in the scene, so that I can run this code even when
the game is not running. I’ve created a simple sphere in the editor from the menu, and put it in the way of the ray. When I check the rayCast member to do the raycast, the result is as expected, I can see in the log:
hit: Sphere (UnityEngine.SphereCollider) at 6.538455
Now I start the game, which creates a lot of objects in the scene, but leaves the test sphere intact. I pause the game, and do the raycast again, the result is still as expected, as the sphere is the first in the way of the ray.
hit: Sphere (UnityEngine.SphereCollider) at 6.538455
Now I delete the sphere while the game is paused, do the raycast again. I got a hit, but not the object I was expecting, something further down in the way of the ray. Now the interesing part. While the game is still paused, I create the sphere again the same way I was creating it in the beginning of the test, same transformation same everything, to the raycast again, and it does not hit the sphere. During the whole test the game is paused, so no Update function messes up things in the background for sure. Can anyone explain why the ray is missing objects incuding the sphere I created while the game was running? Thanks in advance.