|
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:
Component | Accessible as |
---|---|
Transform | transform |
Rigidbody | rigidbody |
Renderer | renderer |
Camera | camera (only on camera objects) |
Light | light (only on light objects) |
Animation | animation |
Collider | collider |
... 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.
transform.Translate(0, 1, 0);
// is equivalent to
GetComponent(Transform).Translate(0, 1, 0);
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Example() {
transform.Translate(0, 1, 0);
GetComponent<Transform>().Translate(0, 1, 0);
}
}
import UnityEngine
import System.Collections
class example(MonoBehaviour):
def Example():
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.
// This finds the script called OtherScript in the same game object
// and calls DoSomething on it.
function Update () {
var otherScript: OtherScript = GetComponent(OtherScript);
otherScript.DoSomething();
}
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Update() {
OtherScript otherScript = GetComponent<OtherScript>();
otherScript.DoSomething();
}
}
import UnityEngine
import System.Collections
class example(MonoBehaviour):
def Update():
otherScript as OtherScript = GetComponent[of OtherScript]()
otherScript.DoSomething()