@@ -225,7 +225,7 @@ private void RaycastUnityUI()
225225 // Graphics raycast
226226 raycastResultList . Clear ( ) ;
227227 EventSystem . current . RaycastAll ( UnityUIPointerEvent , raycastResultList ) ;
228- RaycastResult uiRaycastResult = FindFirstRaycastInLayermasks ( raycastResultList , RaycastLayerMasks ) ;
228+ RaycastResult uiRaycastResult = FindClosestRaycastHitInLayermasks ( raycastResultList , RaycastLayerMasks ) ;
229229 UnityUIPointerEvent . pointerCurrentRaycast = uiRaycastResult ;
230230
231231 // If we have a raycast result, check if we need to overwrite the 3D raycast info
@@ -287,32 +287,35 @@ private void RaycastUnityUI()
287287 #region Helpers
288288
289289 /// <summary>
290- /// Find the first ( closest) raycast in the list of RaycastResults that is also included in the LayerMask list.
290+ /// Find the closest raycast hit in the list of RaycastResults that is also included in the LayerMask list.
291291 /// </summary>
292292 /// <param name="candidates">List of RaycastResults from a Unity UI raycast</param>
293293 /// <param name="layerMaskList">List of layers to support</param>
294294 /// <returns>RaycastResult if hit, or an empty RaycastResult if nothing was hit</returns>
295- private RaycastResult FindFirstRaycastInLayermasks ( List < RaycastResult > candidates , LayerMask [ ] layerMaskList )
295+ private RaycastResult FindClosestRaycastHitInLayermasks ( List < RaycastResult > candidates , LayerMask [ ] layerMaskList )
296296 {
297297 int combinedLayerMask = 0 ;
298298 for ( int i = 0 ; i < layerMaskList . Length ; i ++ )
299299 {
300300 combinedLayerMask = combinedLayerMask | layerMaskList [ i ] . value ;
301301 }
302302
303+ RaycastResult ? minHit = null ;
303304 for ( var i = 0 ; i < candidates . Count ; ++ i )
304305 {
305306 if ( candidates [ i ] . gameObject == null || ! IsLayerInLayerMask ( candidates [ i ] . gameObject . layer , combinedLayerMask ) )
306307 {
307308 continue ;
308309 }
309-
310- return candidates [ i ] ;
310+ if ( minHit == null || candidates [ i ] . distance < minHit . Value . distance )
311+ {
312+ minHit = candidates [ i ] ;
313+ }
311314 }
312315
313- return new RaycastResult ( ) ;
316+ return minHit ?? new RaycastResult ( ) ;
314317 }
315-
318+
316319 /// <summary>
317320 /// Look through the layerMaskList and find the index in that list for which the supplied layer is part of
318321 /// </summary>
0 commit comments