Skip to content

Avoid null comparisons against UnityEngine.Object subclasses

Matt Ellis edited this page Feb 19, 2019 · 3 revisions

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 or Awake. This will introduce a field to hold the result and move the comparison to Start or Awake.

This inspection was first added in Rider/ReSharper 2018.3

Clone this wiki locally