Relating Scripts to the Scene

We know how the script works in a vacuum. That won’t do us any good, though, because we haven’t attached any of the scripts to the scene. We may have a script that tells our player character to jump when the up arrow is pressed, but how does the script know what the player character is?
Well, we have a few methods of introducing objects to scenes.

Attaching Scripts

This method is quite easy. We just have to create a Script component in the GameObject we want, then drag and drop the script into the component.
By doing this, we’re making the script relate directly to the object. This means that transform applies directly to that object, so calling something like transform.position would return the position of the object that the script is on.
Different objects can have the same script, but each script will be treated on a case by case basis. For example, if GameObject A had Script A and GameObject B had Script B, then calling the same transform.position command on both would return Position A and Position B for each instance of the script.
This method is useful when we want multiple scripts to compare different objects. For example, we can create five different scripts to handle five different types of movements, without being caught up in similarities and differences by making one script. There are times when we want to do that, though, and that brings us to the next method:

Declaring GameObjects in Scripts

This method requires a little more work. To do this, the script has to already be attached to a GameObject like in the first method, so in a way this is just an extension of the first method. Then, in the class, we declare GameObjects as public class variables.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NewBehaviourScript : MonoBehaviour { public GameObject test; public GameObject test2; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
This creates two empty slots in our script component, which we can fill with the respective GameObjects.

Finding GameObjects

This is kind of an extension of the second one (again, they’re all very interconnected and you’re expected to use all as you see fit), but the way you do this is by using the command GameObject.Find(String). Not much else to say here, this just lets you relate to a GameObject in code, and you still have to have a class variable to hold that GameObject, unless holding it is just temporary.
You may notice that we haven’t gone into many of the specific code segments that one might use. And there is a reason for this.
The Unity library is so massive that we cannot even begin to cover everything in this one lesson. Thus, the other types of code will be handled on a case by case basis, and if you need anything more, you can look at the Unity Documentation. It’s really very thorough.