Find.GetComponent vs. FindObjectOfType

So maybe this is just my learning curve showing itself, but from the documentation, I have been using a lot of code like:

GameObject.Find("object").GetComponent(Script)

Then I recently discovered:

GameObject.FindObjectOfType(Script)

So my question is, is there a performance difference between the two?

And, assuming that the script instance is unique in your scene, is there any other reason not to use the shorter version?

I read at one point that any Find call takes some overhead, so that if the object is going to be invoked repeatedly, it’s better to assign the Find results to a variable and keep it. But then I also read that can consume memory.

In our case, most of these calls are not being executed every frame – it’s usually a user action or AI trigger.

Both seem to work well enough, but I just wanted to make sure we weren’t committing some blunder with performance.

Thanks,
Steve[/code]

The performance is probably negligible if this is only being called when triggered by an event. I don’t like to use FindObjectOfType because a.) there is no guarantee which instance of the type you’re getting, it’ll always be the first occurrence of an instance of that type in scene (first meaning first instantiated?). I’d only use it if you know there is only one instance of that type.

On the other hand, FindObjectsOfType is very useful when you need to get all the instances of a specific type in the scene :slight_smile:

1 Like

Thanks.

Yes, I’m only doing that in the case where I know there’s only one instance of the object.

The few bytes it takes to save the result to memory far outweighs having to call Find() with strings each time. On the other hand, cached variables can lead to issues when the object is renamed, or destroyed…

Nine years later and the answer is the same.

1 Like

nice necromancer post :slight_smile:

ummmm…