Use GetComponent or public variables.

I heard a tutor say that GetComponent is a very slow operation and you should avoid using it many times. So I thought - why not use it at all? Because I can declare a public variable of the component/object I want to access, and drag the object with that component in the empty box in the editor. I was just wondering if there is any performance difference between using GetComponent in the Start/Awake method and declaring public variable and assigning the object/component inside the editor.

On top of technical difference what you might want to know is that there is paradigmatic difference between the two. Both are about getting a reference (dependency) to something. But the difference is where the dependency wiring happens: in place or centrally.

In place: you fetch an object from within where ever you need it. This is mostly done with all sorts of Find() and GetComponent(). This pattern is called Service Locator.

Centrally: there is a central hub of wiring things up. In your case the hub is the human programmer with a mouse utilizing Unity Inspector. There are solutions where the human is replaced with an xml file, dependency graph, etc. This pattern is called Dependency Injection.

Now that you are familiar with the terms, you are free to browse the Internet and see pros and contras of either, for instance:

On top of paradigmatic differences of the two you have to always keep an extra layer of differences brought onto you by Unity in mind.

Which one to use? I would personally always vote for dependency injection. It’s not always easy, not always convenient, and service locator is a very tempting quick’n’dirty alternative, but I still would. I will also have many to disagree.

If you know exactly which object’s component’s variable you want to get, feel free to drag it in the inspector. But if you don’t know or you’re instantiating the object, you have to use GetComponent. There’s not much performance difference.