Question: Why use GetComponent instead of defining Animator animator;?

At 10:30 in the video, Rick uses

GetComponent<Animator>().SetBool("isAttacking", true);

Is there a specific reason this is done instead of going up to the top and putting in

Animator animator;

and then in the method using

animator.SetBool("isAttacking", false);

Is this strictly for demonstrative purposes? Or is there a meaning to the change in how it was written, because in the only other example of this during the lesson he uses the latter instead of the former. I think they do the same thing but I often get confused as to which I am supposed to be using between:

Type nameOfType;

or using:

GetComponent<Type>();

Any insight into purpose or reasoning would be appreciated. Even if this is just a personal style I would be interested in learning why.

Hi Ivicus,

That’s a good question. How many times does GetComponent<Animator>() get called during the lifetime of the object in Rick’s solution? More than once? If so, it makes sense to optimise the code by caching the reference to the Animator.

Since this course caters to beginners and since our games are very small, Rick does not focus on performance optimisation.

Nevertheless, feel free to cache the reference. :slight_smile:

So if I understand correctly, if a reference is only used once or maybe twice within an object, it is okay to GetComponent<>(), but generally speaking, I should default to cache-ing the reference for optimization reasons? I presume this is because once a game gets large (or there are a lot of objects) it can cause a game to run less smoothly, perhaps dropping frames and the like.

Thanks as always Nina!

-Andrew

That’s correct, Andrew. GetComponent and (even worse) the Find methods are fairly expensive. For this reason, it is always a good idea to cache the reference if you access an object more than once. The earlier you get used to it, the better.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms