-
Notifications
You must be signed in to change notification settings - Fork 134
Avoid null comparisons against UnityEngine.Object subclasses
Classes deriving from Unity.Object
inherit equality operators that change the behaviour of the ==
and !=
operators. While these operators will perform standard .NET reference equality, if comparing one side to null
, these operators will call native code to check if the underlying native engine object is still alive. For more details on the background of this, please see the explanation of the "Possible unintended bypass of lifetime check of underlying Unity engine object" inspection.
This transition to native code can be expensive, as Unity will perform lookups and validation to convert the script reference to the native reference. While small, the cost of comparing a Unity object to null
is much more expensive than a comparison with a plain C# class, and should be avoided inside a performance critical context, and inside loops.
This inspection will add a performance indicator highlight to null
comparisons against UnityEngine.Object
subclasses inside a performance critical context. It will also provide the following Alt+Enter context actions:
- Move outside loop. This will introduce a variable to hold the result and move the comparison outside the scope of a loop.
- Move to
Start
orAwake
. This will introduce a field to hold the result and move the comparison toStart
orAwake
.
This inspection was first added in Rider/ReSharper 2018.3