From what I understand I can specify an object with “other.gameObject.name” which goes off of the name given to an object, and you can you use “other.gameObject.tag” to specify an object by a given tag.
I’m not sure when I should use one or the other or what the benefit of one is.
My question is which should I use and when?
Tags are used to identify groups of objects. For example, say you’re making a sports game, and you have a “red” team and a “blue” team. Each player on both teams can have an individual name, but would have either a “red” tag or a “blue” tag in order to tell which team they’re on.
Tags are just one more way of grouping things. A way of saying these 10 gameObjects all “count as” pickups, or enemies (or red or blue teams.) Don’t go out of your way to use them. Eventually, you might be writing some code and want to ask “does the thing that hit me count as being catchable?” and tags might help.
Tags don’t do anything by themselves, except give your code something to read. Layers seem like tags but they can affect Physics and raycasting, so you often have to set layers a certain way. For example, ghosts are on a layer to go through walls, and orcs aren’t, but you can use tags to say they’re both monsters.
You never have to use tags. For example, you could have all enemies’ gameObject names start with an E, and check that. But giving them all an “enemy” tag might look nicer. Or give them a script, and put type info in variables (tags hold just one piece of info – a script can hold all you want.)
Speed-wise, don’t worry. Even though tags are strings, I think they get converted into integers when using
CompareTag. So a tag look-up is maybe faster than a name look-up. But that tiny possible speed isn’t worth confusing code. Plus, you never do name lookups once you learn to compare transforms.