Setting GameObject Variable

I’m having trouble figuring out how to set a GameObject variable to equal an in scene game object on runtime. I’d like it to be set via the name, but I could also use tags if that is easier.

Generally, you don’t want to search for a GameObject by name or tag if you can avoid it (if you have to, searching by tag is more efficient than by name).

If the GameObject was instantiated during runtime, whatever created the object will have a reference to it, and can pass that reference to whatever needs to access that GameObject. However, if the object is part of the scene when the scene begins (i.e. you made the object in the scene editor), you can get a reference to that object by linking that object to one of your scripts in the inspector (see “Accessing Other Objects” in this page of the Unity Manual) to see how to do this.

Once you have a reference to a GameObject, if you need to access the components and scripts on that object, you can use the GetComponent function, i.e.

BoxCollider2D box = object.GetComponent<BoxCollider2D>();
MyScript scriptVar = object.GetComponent<MyScript>();

Alternatively, you can use inspector linking to get references directly to the components on the object instead of the object itself.

You have 2 options:

  1. Create a variable of the GameObject and drag the reference to it in the inspector.

  2. Search by tag using GameObject.FindWithTag

Of the two options, the first one is the fastest. If you really need to, use the second option (if the reference object constantly changes or only exists at runtime). Never, ever, search by name; use tags instead.

Also, (unless intentional) never assign references per frame for performance reasons.