Now that we know how components act on GameObjects, how do we go about accessing their specific instances? Lucky for us, all GameObjects in Unity inherit from the GameObject class, which means we can use their member methods to find anything we need in a scene. There are two ways to assign or retrieve GameObjects that are active in the current scene:
- Through the GetComponent or Find methods in the GameObject class, which work with public and private variables.
- By dragging and dropping the GameObjects themselves from the Project panel directly into variable slots in Inspector tab. This option only works with public variables in C# (or in Unity with private variables marked with the SerializeField attribute), since those are the only ones that will appear in Inspector.
You can learn more about attributes and SerializeField in the Unity documentation at https://docs.unity3d.com/ScriptReference/SerializeField.html.
Let's take a look at...