Im watching Code Monkeys course KitchenChaos, and there he uses RaycastHit to get colider in front. But if collider is hitted, on every single frame he uses TryGetComponent:
if (Physics.Raycast(transform.position, lastInteractDir, out RaycastHit raycastHit, interactDistance, counterLayerMask))
{
if (raycastHit.transform.TryGetComponent(out ClearCounter clearCounter))
{
clearCounter.Interact();
}
}
Is it more performant to use GameObject.tag instead? I know it’s bad identifying, or maybe there’s another way then using GetComponent every single frame? Or it’s not that much sacrifice resources…
A few Try/GetComponent calls per frame is never going to be a performance concern. Don’t get cought up in speculative optimisation. 99% of the time it’s unnecessary.
An object can only have one tag, but any number of components. Using components is always going to be the cleaner and more flexible approach.
Tags are just a very old part of Unity that are still around. They could be removed and we wouldn’t lose anything of value.
1 Like
Thank you for fast replying, but even if it’s mobile development?
Maybe 10 years ago, but phones are pretty powerful these days.
In any case, don’t speculate, test. You’ll probably find your concerns are barely a blip on the profiler.
2 Likes