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 How to Make a Video Game Score, Enemies, and Game State Script the Score Counter

GetComponent in a class

How are we calling GetComponent<Text> on this video?

Does GetComponent automatically know that we're referencing the current object we're in, kinda like "this" does in JavaScript?

Thx

1 Answer

George Vardikos
George Vardikos
6,889 Points

When we create a new script we attach it to a Game Object. That's how the compiler knows to which Object we refer to, so there is no need for adding the "this" keyword. However, if you add it is not wrong, just it is not necessary.

More specifically to your question, by calling GetComponent<...> we calling a block of code which inside of it I suppose it uses the "this" keyword.

So yes everytime that we call GetComponent from a script attached to a GameObject it knows automatically that we are referring to the current game object