- Home /
What are the differences between Physics.Raycast and Physics.RaycastNonAlloc ?
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 !
Answer by Bunny83 · Jul 13, 2016 at 12:08 AM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220612084722im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Does writing to Mesh arrays cause allocation? 0 Answers
C# - Raycast Bullets Object Pooling (please help) 0 Answers
Character Controller 2D physics or raycast ?? 1 Answer
GC Allocation with new array length 0 Answers
large sudden profiler spike 0 Answers