-
Notifications
You must be signed in to change notification settings - Fork 134
Avoid using allocating versions of Physics Raycast functions
The ray casting and collision detection methods in the Physics
and Physics2D
objects that return arrays will allocate the array on each call, which can affect performance, especially if called frequently. Unity 5.3 introduced non-allocating versions of these methods that allow passing in a pre-allocated array to collect the results.
This inspection will add a warning to the allocating versions of these methods and provide an Alt+Enter Quick Fix to rewrite the call to the non-allocating version, leaving the text caret in a location to reference an existing array.
The relevant methods on the Physics
class are:
-
Physics.BoxCastAll
→Physics.BoxCastNonAlloc
-
Physics.CapsuleCastAll
→Physics.CapsuleCastNonAlloc
-
Physics.RaycastAll
→Physics.RaycastNonAlloc
-
Physics.SphereCastAll
→Physics.SphereCastNonAlloc
-
Physics.OverlapBox
→Physics.OverlapBoxNonAlloc
-
Physics.OverlapCapsule
→Physics.OverlapCapsureNonAlloc
-
Physics.OverlapSphere
→Physics.OverlapSphereNonAlloc
and for Physics2D
:
-
Physics2D.BoxCastAll
→Physics2D.BoxCastNonAlloc
-
Physics2D.CapsuleCastAll
→Physics2D.CapsuleCastNonAlloc
-
Physics2D.CircleCastAll
→Physics2D.CircleCastNonAlloc
-
Physics2D.LinecastAll
→Physics2D.CapsuleCastNonAlloc
-
Physics2D.RaycastAll
→Physics2D.RaycastNonAlloc
-
Physics2D.GetRayIntersectionAll
→Physics2D.GetRayIntersectionNonAlloc
-
Physics2D.OverlapAreaAll
→Physics2D.OverlapAreaNonAlloc
-
Physics2D.OverlapBoxAll
→Physics2D.OverlapBoxNonAlloc
-
Physics2D.OverlapCapsuleAll
→Physics2D.OverlapCapsuleNonAlloc
-
Physics2D.OverlapCircleAll
→Physics2D.OverlapCircleNonAlloc
-
Physics2D.OverlapPointAll
→Physics2D.OverlapPointNonAlloc
Note that the size of the array determines the maximum number of results collected by these non-allocating methods. The methods do not resize the array, and do not notify if more results would have been returned. It is up to you to choose an appropriate size for this array, either by determining the maximum possible number of results, or by choosing a limit after which further results are no longer useful. If it is important to process all possible hits, the allocating version should be used as the only available option, but it is important to be aware of the performance overhead of repeated allocations. It is possible to suppress this warning using code comments, or by changing the severity of the highlight. (See here and here for the equivalent ReSharper documentation)
For more details, see this Unity document on best practices for performance.
This inspection was first added in Rider/ReSharper 2018.3