When comparing two GameObjects by Tags, it should be noted that the following would cause Garbage Collector overhead as a string is created everytime:
if (go.Tag == "myTag")
{
//Stuff
}
When performing those comparisons inside Update() and other regular Unity's callback (or a loop), you should use this heap allocation-free method:
if (go.CompareTag("myTag")
{
//Stuff
}
Additionally it's easier to keep your tags in a static class.
public static class Tags
{
public const string Player = "Player";
public const string MyCustomTag = "MyCustomTag";
}
Then you can compare safely
if (go.CompareTag(Tags.MyCustomTag)
{
//Stuff
}
this way, your tag strings are generated at compile time, and you limit the implications of spelling mistakes.
Just like keeping tags into a static class, it is also possible to store it into an enumeration:
public enum Tags
{
Player, Ennemies, MyCustomTag;
}
and then you can compare it using the enum toString()
method:
if (go.CompareTag(Tags.MyCustomTag.toString())
{
//Stuff
}