How to access a gameobjects components?

Sometime i can access it like this:
gameObject.transform.position
And sometimes like this:
gameObject.GetComponent<'Transform>().position

What is the difference? why use one way?

2 Likes

Pretty much any component besides the transform will have to be accessed through GetComponent<>(), it is a very powerful tool, transform is the most used component and all GameObjects have it, probably that’s why there is a shortcut gameObject.transform for it, I wouldn’t doubt if the source code for it was something liike this:

public Transform transform {
     get {
         return GetComponent<Transform>();
     }
 }
2 Likes

so “GetComponent<>()” is generally the way to access components?

2 Likes

Yep… with the Type in between the < and > :slight_smile:

1 Like

Yes, that’s right, sometimes you will have to set an reference to which namespace the reference to the component is attached to, for example, if you are trying to access an text, you will have to add using UnityEngine.UI to the top of the script

1 Like

Thanks alot :slight_smile:

2 Likes

Privacy & Terms