I was wondering what the difference was between the transform and gameobject getcomponents.
I looked at this resource here: https://answers.unity.com/questions/1360282/what-is-the-difference-between-gameobjectgetcompon.html
It states that: "At the end, both are the same"
Surely there must be a difference between the two?
You can consider the GameObject as a place holder of different components and Transform is a specific component. So now in your case you can Instantiate by referencing the GameObject as a whole or its Transform component.
Caching GetComponent Accesing a GameObject's components is usually done with the GetComponent function. This function is expensive in terms of calculations. This example is much better.
GetComponent<T> is semi-fast. However, if you can cache the reference, do it. You'll save a decent amount of CPU time.
GetComponent will return the first component that is found and the order is undefined. If you expect there to be more than one component of the same type, use gameObject. GetComponents instead, and cycle through the returned components testing for some unique property.
A GameObject is a container; you add pieces to the GameObject container to make it into a character, a light, a tree, a sound, or whatever else you would like it to be. Each piece you add is called a component.
According to the same question answered over here: this. transform and this. gameObject are both cached in the Component class, which makes them faster than the generic GetComponent<>() counterpart.
GetComponent<T>() is a method, which is not valid in the given context [closed]
They are equivalent.
Keep in mind Unity's component-based architecture: almost everything that exists in the scene is a GameObject which usually has one or more Components attached to it. A Component must be attached to a GameObject in order to exist.
The GetComponent
method, really an entire family of methods, allows scripts to look up references to specific Components.
If you call GetComponent
on a GameObject (such as gameObject.GetComponent
), it will find a matching Component attached to that GameObject.
If you call GetComponent
on a Component (such as transform.GetComponent
), it will find the GameObject that component is attached to, then find a matching Component attached to that GameObject. This is the same result, but it's a convenient shorthand to save you the effort of putting gameObject
references all over your scripts.
Technically these are separate methods, but the results and semantics are essentially identical. In practice you can use whichever form you are more comfortable with.
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