UnityException: Tag is not defined
Console
UnityException: Tag: X is not defined.
Your code used a tag name, in CompareTag, FindWithTag or by setting gameObject.tag, that does not exist in the project's Tag Manager. Unity only accepts tags that are defined there.
Read the Console line first
X is the tag name your code used. Compare its spelling and case with the list in the Tag Manager.
Common causes
The tag was never created
Open Edit > Project Settings > Tags and Layers, or the Tag dropdown on any GameObject, and choose Add Tag.
The name has a typo or different case
Tags are case-sensitive: "player" is not "Player".
The fix
Fix
C#
// Keep tag names in one place
public static class Tags
{
public const string Player = "Player";
public const string Enemy = "Enemy";
}
if (other.CompareTag(Tags.Enemy)) TakeHit();Stop it coming back
Use CompareTag rather than tag ==, which is faster, and keep tag strings as constants so a typo becomes a compile error instead of a runtime one.
Questions
- Can I create a tag from code at runtime?
- No. Tags are part of the project's settings and are fixed when you build. Add them in Project Settings > Tags and Layers, or from an Editor script before building.
- Should I use CompareTag or ==?
- Use
other.CompareTag("Enemy"). It is faster and does not allocate a string. It is also the call that reports this error for an undefined tag, which is useful: a typo shows up immediately instead of silently returning false. - Tag or layer: which should I use?
- Tags identify what an object is in your own code. Layers control what physics, raycasts and cameras see. If the check is about collisions or raycasts, use a layer and a LayerMask instead of a tag.
Scripts that avoid it
Related errors
Got a different error? Paste it into the error lookup.