Skip to content

Avoid using allocating versions of Physics Raycast functions

Matt Ellis edited this page Feb 20, 2019 · 4 revisions

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:

and for Physics2D:

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

Clone this wiki locally