Question about gameObject.GetComponent<>

Hi guys. I hear all the time that using “GetComponent<>” in an Update function is a bad idea because it’s slow. And as much as possible it is preferable to cache variable values. Which makes sense.

But what of the cases when my AI detects an enemy (another game object) in an OnTriggerEnter function? And I have to check values in a script that could be attached (or not) on that enemy game object.

So first I have to check if said script is attached to said game object, and then once again to get the value this time. And I use “GetComponent<>” for that.

Is there a way to do without it?

Thanks,
Seith

It’s not particularly slow, and caching it just because of using it once every Update is unlikely to make any difference. Much less so if you’re just using it in OnTriggerEnter. You’d be more concerned with caching it if you’re using it in a tight loop that runs thousands/millions of times at once, for example. In other words, keep using it as you are and don’t worry about it.

–Eric

  1. It’s not a rule, it’s an advice.
  2. There should be the word “relatively” in front of “slow”.

Use GetComponent<> wherever it feels suitable, unless you see it is really slow in your situation.

Ok, thanks guys! I won’t feel bad using it anymore… :slight_smile: