Most advanced game code does not only manipulate a single object. The Unity scripting interface has various ways to find and access other game objects and components there-in. In the following we assume there is a script named OtherScript.js attached to game objects in the scene.
1. Through inspector assignable references.
You can assign variables to any object type through the inspector:
You can also expose references to other objects to the inspector. Below you can drag a game object that contains the OtherScript on the target slot in the inspector.
2. Located through the object hierarchy.
You can find child and parent objects to an existing object through the Transform component of a game object:
Once you have found the transform in the hierarchy, you can use GetComponent to get to other scripts.
You can loop over all children:
See the documentation for the Transform class for further information.
3. Located by name or Tag.
You can use GetComponent on the result to get to any script or component on the found game object
Some special objects like the main camera have shorts cuts using Camera.main.
4. Passed as parameters.
Some event messages contain detailed information on the event. For instance, trigger events pass the Collider component of the colliding object to the handler function.
OnTriggerStay gives us a reference to a collider. From the collider we can get to its attached rigidbody.
Or we can get to any component attached to the same game object as the collider.
Note that by suffixing the other variable in the above example, you can access any component inside the colliding object.
5. All scripts of one Type