I was a bit unsatisfied with the answer to the question earlier about using RaycastAll vs. RaycastNonAlloc so I wanted to discuss this further.
The case here is every frame we want to raycast and then sort the results by distance order.
Using the presented solution, there is an allocation by RaycastAll to create the array of RaycastHit objects and then another in RaycastAllSorted to create the distance array. It fills the need but those allocations, which will become garbage once we exit InteractWithComponent, will add up.
If we instead considered using RaycastNonAlloc, we could avoid these allocations altogether. Rather than allocate two arrays every frame that get immediately discarded, we can allocate two reasonably sized arrays as class-level fields and reuse them. This avoids the allocations and garbage on every frame that the above solution suffers from. ‘Reasonably sized’ can be fairly large to avoid any missed objects and then possibly tuned later.
I see there was also a post that built an interesting utility class that ultimately uses RaycastNonAlloc. Or, that’s a bit much, one might simply modify Sam’s solution to use RaycastNonAlloc directly.