I'd like to know if there's any under-the-hood difference in the execution of these two CompareTag() calls:
private void OnTriggerEnter(Collider otherCollider)
{
if (otherCollider.CompareTag("TestTag"))
{
Debug.Log("The other Collider is tagged: TestTag");
}
if (otherCollider.gameObject.CompareTag("TestTag"))
{
Debug.Log("The other GameObject is tagged: TestTag");
}
}
I suspect they should be identical – a Component is always attached to one and only one GameObject, so it shouldn't be necessary to access the Component's ".gameObject" reference first. Both calls behave identically as far as I can tell.
I wonder because:
If you take a look at the actual code for Component.CompareTag(), you'll see this:
// UnityEngine.Component
/// <summary>
/// <para>Is this game object tagged with tag ?</para>
/// </summary>
/// <param name="tag">The tag to compare.</param>
public bool CompareTag(string tag)
{
return gameObject.CompareTag(tag);
}
So, if you want to get down to the "under the hood" implementation, at a micro-optimisation level, when you call Component.CompareTag(), you're ALSO calling the gameObject property as well, which has it's own processing time associated with accessing it. Now, that processing time isn't huge, but it IS there because properties have similar processing overheads to method calls, as they're essentially the same.
The process then goes Component.CompareTag() -> Component.gameObject{get} -> GameObject.CompareTag().
So, the long and short of it is, that if you can call a method further down the call stack, instead of a top level helper method, you're best to chose the more performant one - GameObject.CompareTag().
As for the example you gave, it's essentially saving one method call, by accessing the Component gameObject property directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With