gameobject.find() or public GameObject variables better?

Hi guys, I am new to unity and playing around with it for some time and i saw people use these 2 to get gameobject:

  1. Drag an object inspector into the public var
    public GameObject aObject;

  2. Use gameobject.find()
    private GameObject _aObject;
    _aObject = GameObject.FInd(“aObject”);

I wonder which is better or faster?
Thanks alot guys…!

Using a public GameObject is generally better. It means that you can rework your project from within the Unity Editor without having to alter your script. It will also make things more obvious (from the unity editor), and allows you to rename your objects as you see fit.

Using any form of .Find is a costly process so you should avoid it whenever you can in terms of optimization. That being said you will have to use it for some projects. If the object is unique and you will only ever have one instance or a controlled instance (such as you want a specific prefab) then you should always use the Editor route. If however you need to find a specific instance, such as the closest of some object type, or an object that isn’t always going to be instantiated in the scene, then you should use some form of .Find.

Neither is “better”. Or, rather, as they’re different tools they’re each “better” for different situations. One is a search function, the other is storage of a variable, so use them for those things.

If you want to use something often then keeping a reference to it (ie: using a local variable) is definitely the better way, because it means you don’t search for it anew every time you want to use it. If you don’t want to use it often or the reference may change between uses then you want to use the search. Or, use both - use the search to find the object and then store the reference in a local variable so you can use it repeatedly without having to constantly look it up.

2 Likes