I read in this thread Do you use tags? and most people don’t like tags
and use components as tags
isn’t getcomponent() more performance expensive than comparetag, in a raycast context, cuz its in the update()?
I read in this thread Do you use tags? and most people don’t like tags
and use components as tags
isn’t getcomponent() more performance expensive than comparetag, in a raycast context, cuz its in the update()?
GetComponent is more expensive than CompareTag (Slightly. It’s actually quite fast). There are other disadvantages of using CompareTag though:
In my experience, these disadvantages usually outweigh a slight performance advantage. The other thing is that often a CompareTag ends up being followed by a GetComponent anyway if you want to interact with the thing you hit in a meaningful way. This means you were going to take the performance hit of a GetComponent anyway, so you might as well use it to check if it’s the thing you care about and skip the CompareTag.
I wouldn’t say one or the other is strictly better. They’re different tools and each will be useful some of the time.
thanks:)
Just going to go all devil’s advocate for a bit…
If the majority of the things you hit aren’t what you care about hitting, then you may actually get a performance benefit from using CompareTag even though you may follow it with GetComponent. For example, you are shooting. You do a CompareTag checking if what you shot is an Enemy. If it is tagged Enemy then you will GetComponent for its health script. But the majority of shots will likely hit terrain or walls instead of objects tagged Enemy, and in those cases you don’t call GetComponent because you don’t change the health of the terrain. Especially if the game is heavy on inaccurate machine guns instead of sniper rifles. Just something to consider. Might be worth testing both approaches in the Profiler.
I also use CompareTag when I have multiple colliders on an object, and I need to do something different depending on which collider I hit, where GetComponent would make that more complicated. But this really isn’t the performance question from the OP.
So basically… understand the differences between the two, understand the advantages and disadvantages of each approach, and choose one or the other depending on your specific use-case!
Above all, don’t fall into the trap of premature optimization. Most of the time you can just pick one and move on with your life.