Raycast continuing to hit destroyed objects?

// Within an Update() method:
   if (Physics.Raycast(_ray, out _rayhit))
   { 
       return; 
   }
   else 
   {
      Debug.Log("Expected when the object that the raycast was hitting is destroyed.");
      // Result: This message does not appear when the object has been destroyed
   }

My mouse cursor reliably does raycasts on objects in the scene and detects the hit object. When an object that the raycast is hitting gets destroyed, then the condition should return false, and I should get the above Debug.Log message, right? Instead the raycast continues to hit the destroyed object. This is odd especially since the raycast is taking place within an Update() method and should cast a new ray every frame.

If it’s hitting something then there is a 3D Collider there so you’re either not destroying the Collider or potentially your ray is hitting something else you don’t expect. You’re not limiting what it’s hitting either so it’ll contact any collider in the scene not limited by layer. Potentially your ray isn’t correct. Stuff to verify anyway.

Thank you. I actually found the issue: A local variable is being set to the last hit collider if a collision is detected… However, when that collider is destroyed, the local variable is automatically set to null rather than raising a null reference exception when used. That caused faulty logic in the way I was using that variable.

private Collider _collider;   // this variable is automatically changed to null instead of raising a null reference exception when its assigned Collider reference is destroyed

Update() {
   if (Physics.Raycast(_ray, out _rayhit))
   {
       if (_collider != _rayhit.collider)  // new collider detected
       {
           _collider = _rayhit.collider;
       }
   }
   else
   {
       if (_collider != null)  // condition never met when collider is destroyed
       {
           Debug.Log("Expected the first frame the collider is destroyed"); // never shows
           _collider = null;
       }
   }
}