Hi Unity Masters !
I was browsing through the Unity documentation and found an alternate function for performing a raycast.
The documentation say that RaycastNonAlloc generate no garbage.
So I just want to
know why we don’t always use it ? It’s better, less work for the garbage collector.
Thanks you !
Well, just like the docs say:
Like Physics.RaycastAll, but generates
no garbage.
Physics.RaycastAll creates and returns an array of RaycastHit structs. This creates garbage on the heap.
RaycastNonAlloc does the same but instead of returning a new array each time it’s called, you have pass a preallocated array to the method and it just fills in the elements. The method just returns an integer that tells you how many hits has been filled in. The array should be large enough to hold all possible hits. The great thing is you can reuse the same array each time you call the method.
“RaycastNonAlloc” can’t be compared to “Raycast” as it does something different. They should have called it RaycastAllNonAlloc, that would have been more clear. However if you read the docs everything should be clear.