- Home /
Why do we use the "transform." in hit.transform.gameObject.tag?
Basically, I created this script, which obviously isn't complete. destroyableObjectFInder is a Physics.overlapSphere. I got the if statement off of the internet, and out of curiosity, why do we use "transform." and not just hit.gameObject.tag? Is it because transform is found in all objects, kind of like how child objects are accessed through the parents transform?
foreach(Collider hit in destroyableObjectFinder)
{
if (hit.transform.gameObject.tag == "Obstacles")
{
}
}
Answer by rufopufo · Sep 25, 2020 at 07:18 AM
Hi there,
You should be able to use "hit.gameObject". It is unnecessary the use of transform there.
You can check the API on Collider and you will find out that gameObject is a property inherited, as it is transform.
Hope it helps.
Right every Component has a gameObject property which holds the parent gameobject reference. Transform, Collider, $$anonymous$$onoBehaviour, Rigidbody, ... are all Components.
Though every component also has the tag property as well (and the CompareTag method which is more performant) so you don't go through the gameobject and can directly do
if (hit.CompareTag("Obstacles"))
Note that the "tag" property will allocate memory for the tag string because the tag is stored on the native C++ side. So whenever you read that property Unity has to create a managed string for you. CompareTag essentially reverses the information flow. Instead of pulling the tag from native land into managed land, we can simply pass a pointer to our managed string to the native code and Unity does the comparison in native code without the need of any memory allocation.
Your answer
Follow this Question
Related Questions
Sharing components amongst different gameobjects 1 Answer
Often when loading level the Layers i have on gameobjects reset to default. Please help? 1 Answer
Unable to change Tag of Gameobject using Script 1 Answer
Instantiating a Rigidbody instead of a GameObject 1 Answer
Grabbing all Children and components of those children 1 Answer