Which is more efficient GameObject.Find() or public GameObject??

There are two approaches of getting access to a game object in a script:

  1. GameObject.Find()
  2. public GameObject object (and then drag the game object in the inspector)

Can anyone tell me which is more efficient?
I am working on a game and i need to turn of lots of gameObjects to optimize the performance. I know that i can do it both ways but which one will be more efficient performance wise ??

I did find one question but i am looking for a more detailed answer :slight_smile:

Assigning in the inspector is by far more efficient in terms of speed.

GameObject.Find loops through all existing GameObjects and compares their names. Persisted direct links are basically free and initialized when the scene is loaded.

Said that, direct assignments have a couple of draw-backs:

  • You need to remember to assign them, which can become quite a burden depending on your workflow.
  • You can only reference objects that are already present in the editor. So e.g. if you dynamically create objects from script code later, these can not be assigned in the editor (obviously).
  • The pointer use up (very few) memory in the component you need them. This is usually of no real concern, but if you plan to have a LOT of links which you need only once at a blue moon, it might be better to only search them at the time you need them.
  • If you reference any Asset (Texture, Mesh etc) or any prefab that contains an asset, this will be loaded immediately when the scene is loaded. (Of course, GameObject.Find() is not an alternative to direct links here. You need Resources.Load instead and place the assets into Resources/ folder. Just saying… :wink: )

The more efficient is GameObject.FindWithTag()

GameObject.Find is great when you have a small scene.
GameObject.FindWithTag is better for larger scenes with 100s of gameObjects.

public static Object FindObjectOfType(Type type);
is useful somewhere, when you have a small scene and you want to find which object has that specific Type. It helps in refactoring other codes.