Overview: Accessing Other Components Manual     Reference     Scripting  
Scripting
Overview: Accessing Other Components

Components are attached to game objects. Attaching a Renderer component to a game object is what makes it render on the screen, attaching a Camera turns it into a camera object. All scripts are components thus they can be attached to game objects.

The most common components are accessible as simple member variables:

ComponentAccessible as
Transformtransform
Rigidbodyrigidbody
Rendererrenderer
Cameracamera (only on camera objects)
Lightlight (only on light objects)
Animationanimation
Collidercollider
... etc.

For the full list of predefined member variables see the documentation for the Component, Behaviour and MonoBehaviour classes. If the game object does not have a component of the type you wish to fetch, the above variables will be set to null.

Any component or script attached to a game object can be accessed through GetComponent.

JavaScripts
transform.Translate(0, 1, 0);
// is equivalent to
GetComponent(Transform).Translate(0, 1, 0);

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
void Awake() {
transform.Translate(0, 1, 0);
GetComponent<Transform>().Translate(0, 1, 0);
}
}

import UnityEngine
import System.Collections

class example(MonoBehaviour):

def Awake():
transform.Translate(0, 1, 0)
GetComponent[of Transform]().Translate(0, 1, 0)

Note the case difference between transform and Transform. The former is a variable (lower case), the latter is a class or script name (upper case). This case difference lets you to differentiate variables from class&script names.

Applying what we have learned, we can now find any script or builtin component which is attached to the same game object using GetComponent. Please note that to make the following example work you need to have a script called OtherScript containing a function DoSomething. The OtherScript script must be attached to the same game object as the following script.

JavaScripts
// This finds the script called OtherScript in the same game object
// and calls DoSomething on it.

function Update () {
var otherScript = GetComponent(OtherScript);
otherScript.DoSomething();
}

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
void Update() {
System.Object otherScript = GetComponent<OtherScript>();
otherScript.DoSomething();
}
}

import UnityEngine
import System.Collections

class example(MonoBehaviour):

def Update():
otherScript as System.Object = GetComponent[of OtherScript]()
otherScript.DoSomething()