Skip to content

Use CompareTag instead of explicit string comparison

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

The tag property returns a string value that can be used to identify one or more game objects (see the documentation for more details on tags). However, this property causes an allocation each time it is accessed, as the string is copied from the Unity native object into a managed C# string.

This inspection will highlight an explicit string comparison to tag, such as:

if (gameObject.tag == "Tank")

It also provides an Alt+Enter quick fix to convert this comparison into a call to CompareTag(string), which is a native Unity engine method call and so avoids the memory allocation:

if (gameObject.CompareTag("Tank"))

However, it should be noted that CompareTag has a minor difference in behaviour - at runtime, it will check that the tag exists, and will report an error in the Unity console if it does not. This is not a change in Unity policy - tags should exist before being used - but simple string equality does not allow a check to occur.

For more details, see the section on CompareTag in Optimizing Garbage Collection in Unity Games from Unity, and this answer on Unity's forums.

You can’t perform that action at this time.