So in unity, I have found that I can reference other gameObjects through two different ways. Lets say I’ve got a gameObject called “ball” with a script “Ball” attached. Lets say I have another gameObject called “paddle” and I want to reference ball in paddle’s awake function. I could write
public GameObject ball
public Ball ball
And I could drag the ball gameobject into the inspector for the paddle, and under both conditions it would be the same. So what is the difference here? If I wanted to access non-static methods attached to the ball gameObject’s Ball script, would that only work with ‘public Ball ball’ reference?
Is the similarity only evident if all you have to do is reference the gameobject itself and not the script?
Thanks for reading!
If a gameobject has a script attached, it’s always better to use a reference to the script instread of a reference to the GameObject. The reason is simple. Every component has a reference to the gameobject it’s attached to. You can access it by using the
.gameObject property. That GameObject reference is easy to get since a Component has a one-to-one relation to it’s gameobject.
The GameObject is the most important class, but also the most useless. The GameObject is just a container and all it provides is a “name”, “tag”, “layer” and a way to add / remove components. The components actually make up the object in the first place. The GameObject is just the link that holds everything together,
When you store a GameObject reference you’ll have to use
GetComponent<YourComponentClass>() to get a reference to a certain component. GetComponent has to actually search for the given component type on the gameobject. It’s not that bad but should be avoided if possible. That’s why it makes sense to directly store the most useful / most used component in your variable.
If there are other scripts or components on the same object you need to access you can also add some public variables to the script. That way you can directly access those components without the need of GetComponent.
When you create a prefab that has a “self reference” (a reference to another component on the object or one of its childs), those references will be “corrected” when the prefab is instantiated. So you can setup very complex objects and have it’s components linked in the editor.
So i would always suggest that you use
public Ball ball;
When you really need access to the GameObject you can always use
Also keep in mind that the Component type itself (from which all components including your scripts are derived from) also has a GetComponent method. So you can easily search for other components by using a component reference.
Rigidbody rb = ball.GetComponent<Rigidbody>();