Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Game Development

nadav margalit
nadav margalit
5,123 Points

Unity - GetComponent<>

I am watching Unity tutorial and I didn't quite understand what GetComponent<> does.

I tried to read the unity's documentation for it, but I still didn't get it.

if someone can simplify it for me, it will be very helpful to me.

this is the script with the GetComponent:

private Animator playerAnimator; private Rigidbody playerRigidbody;

// Use this for initialization
void Start () {
    playerAnimator = GetComponent<Animator>();

    playerRigidbody = GetComponent<Rigidbody>();

}

1 Answer

Glen Hayes
Glen Hayes
5,798 Points

The GetComponent method simply "selects" the nominated variable you have created for that game object ie private Animator playerAnimator where the GetComponent playerAnimator type will allow access to the animator component of the requested gameObject so you can then use it in your methods. For instance, you first need to access the rigid body game object of your model using the GetComponent method before you can code in a movement method for said character.

Its essentially assigning the rigid body or animator of the game object to your newly created variable.