1
\$\begingroup\$

As far as I know, there are two built in ways to get an instance of a component in Unity.

1 - Serialize the field and drag in the component manually in the editor

[SerializeField] private MyScript script;

2 - Using MonoBehaviour's GetComponent method

script = GetComponent<MyScript>();

I would think that it is more efficient to drag the component in the editor lest making the engine illiterate through every component in the GameObject to find the component.

Is it more or less efficient to drag the component in the editor compared to using GetComponent? Or does Unity find components in a different way or dragging components in the editor is handled in a different way such that it would be more efficient to use GetComponent? Would using one over the other have any impact on performance in the real world?

A similar question would also be raised regarding GameObject.FindGameObjectWithTag() vs dragging in the editor.

As far as optimization go, should you use one method over another?

\$\endgroup\$
1
  • \$\begingroup\$ It seems like we get a lot of questions that turn out to be problems with components referenced by serialized fields, but that could be my imagination. \$\endgroup\$
    – jzx
    Aug 4, 2015 at 4:34

1 Answer 1

6
\$\begingroup\$

Use the inspector to allow the user (you, or other developers) to be able to easily define the Component themselves without having to modify your code.

Use the GetComponent() method if there is no need to be able to change it from the way you designed your script.

Efficiency doesn't have to do with it.

If you use GetComponent() in your script, you will generally store the component in a variable so that it is cached for reuse in your script, so it works out to be the same thing in terms of efficiency.

Where GetComponent() is slow, is if you are calling it as you need it to look up the component every update or something. Store it in a variable and then it's just fine.

Same goes for the FindObject methods. Cache it when your script starts, then it has no impact during runtime.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .