GameObject.FindObjectOfType<Animator>() vs this.GetComponent<Animator>()

In Shooter.cs around the 4 minute mark, we find the animator like this:

animator = GameObject.FindObjectOfType<Animator>();

I read that the GameObject searches the whole scene, which can become slow.

Would it be better to do this?

animator = this.GetComponent<Animator>();

(Both worked for me)


What really baffled me is if GameObject does in fact search the whole scene, wouldn’t it find multiple animators everywhere? How would it know which ‘one’ to grab? I can’t wrap my head around why FindObjectOfType works. The GetComponent makes sense.

@tepkool01 - same here, I used GetComponent but did not realise this was better for performance, just how I thought to do the challenge. Be interested to see the discussions around this.

1 Like

True, the first one checks the whole scene and returns the first found gameobject with an animator component on it. The second way aske the game object itself (this) to return the first animator component on itself.

Thanks for the input on this! I was having issues every so often with the Animator trying to be called after it was destroyed with my shooters once I had 2 or more firing from the same x axis. It was as if the updater was having trouble keeping up with too many defenders firing their weapons and trying to keep track of all the animators destroying and reappearing.

Trying your method seemed to completely fix that issue as it is much less burdensome and more efficient…THANKS!

Glad to see I wasn’t the only who did that! I didn’t even use “this”. I put:

anim = GetComponent<Animator> (); 

And it works fine.

This change also fixed a problem I was having where the shooter script was only updating the animator bool “isAttacking” on the cactus and not the gnome. I changed it from

GameObject.FindObjectOfType<Animator>();

to

this.GetComponent<Animator>();

and now it works on both of them.

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

Privacy & Terms