Introduction
This article belongs to the series about finding GameObjects and Components references from the scene in Unity, in this series we will see different techniques to find from a Script any object that is in the hierarchy in a certain scene in Unity, this is something very important to understand and know how to do it because if we have the reference of an object or component, we can access it and read any public data or execute any public function we need.
Here you have the playlist about finding the references in Unity, in that list we will be adding videos with more and more specific techniques. The following video talks about the technique shown in this article:
All the IMPORTANT information is summarized in the following TUTORIAL FROM MY YOUTUBE CHANNEL
Initial conditions
We start from a Script called “FindReferenceOfAnObject” in which we are going to find the reference of a certain GameObject that is in the scene in Unity, inside the Script we will use that reference to print its name in console with the instruction of the line 13 of the figure 1.
The hierarchy of the scene that we are going to use is composed by the GameObjects that are shown in figure 2, the object “Script-GameObject” is the one that has the Script in figure 1 assigned and it is the one that will be in charge of finding the references, in figure 3 you can see the inspector of this GameObject, where the Script is assigned.
The “GDT (Object to Find)” object seen in figure 2 is the object we want to find from the script, so if we succeed we should see the name of this object printed on the console.
Find the reference of a GameObject that is a child of another GameObject
Maybe we are interested in obtaining the reference of a GameObject that we know is as a child of another GameObject whose reference we have, for example in figure 4 we see that the object to be found is as a child of the GameObject that has the script assigned to it, so if we have the reference of the father object we can access it and apply different actions on it, including accesing to its childs.
The “transform” field is another variable that is defined in all MonoBehaviour and refers to the Transform component of the GameObject to which the script is assigned.
We can use the Transformation to access the children that have that GameObject, using the GetChild() method with parameter 0 of the Transform class, this results in the transformation of the first child that has the GameObject to which this script is assigned, but as we are interested in obtaining the reference of the GameObject not its Transformation, we use the dot operator and the “gameObject” field.
The instruction is as shown in line 4 of figure 5.