Comparing tags the slow way?

One Unity method that stops making garbage.

Comparing tags the slow way?

The problem

Reading .tag makes a string.

void OnTriggerEnter( Collider other ){    if ( other.tag == "Enemy" )        TakeDamage();}

Every time you read .tag, Unity creates a brand new string.

Why it matters

Garbage causes hitches.

Each new string is garbage. When the garbage collector cleans up, the game can stutter for a frame.

1 trigger
1 new string
100 triggers a second
100 new strings

The fix

Use CompareTag.

void OnTriggerEnter( Collider other ){    if ( other.CompareTag( "Enemy" ) )        TakeDamage();}

Same answer, no new string.

The rule

Compare tags. Don't read them.

Checking a tag
CompareTag
Reading .tag
allocates
Matters most
triggers, Update