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.

组件附属于游戏物体.把一个 Renderer (渲染器)组件附到游戏对象,可以使游戏对象显示到场景,附一个 Camera (摄像机)可以把物体变成一个摄像机物体.所有脚本都是组件,因此都能附到游戏对象上.

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.

要看所有的预定义成员变量,请查看文档 Component , Behaviour MonoBehaviour 类.如果游戏对象中没有你想要取得的组件类型,上面的变量值将为null.

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

附在游戏对象上的组件或脚本可以通过GetComponent获取.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
	void Awake() {
		transform.Translate(0, 1, 0);
		GetComponent<Transform>().Translate(0, 1, 0);
	}
}
transform.Translate(0, 1, 0);
// is equivalent to //相当于
GetComponent(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.

注意transform 和 Transform 的差异.前面是一个变量(小写),后面是一个类或脚本名称(大写).这个不同之处可以让你区分变量,类和脚本名称.

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.

应用我们学到的,我们现在能使用 GetComponent 找到附在游戏对象上的脚本或已有的组件.请注意下面的例子,假设你要调用一个名叫OtherScript的脚本,它包含有一个函数DoSomething. OtherScript脚本要附于下面脚本所在的同一游戏对象上.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
	void Update() {
		System.Object otherScript = GetComponent<OtherScript>();
		otherScript.DoSomething();
	}
}
// This finds the script called OtherScript in the same game object
// 这个获得同一个物体上的OtherScript脚本
// and calls DoSomething on it.
// 访问他的 DoSomething .
function Update () 
{
    otherScript = GetComponent (OtherScript);
    otherScript.DoSomething();
}

最后修改:2011年5月16日 Monday 21:49

本脚本参考基于Unity 3.4.1f5

英文部分版权属©Unity公司所有,中文部分© Unity圣典 版权所有,未经许可,严禁转载 。