Component.GetComponent 获取组件


function GetComponent (type : Type) : Component

Description描述

Returns the component of Type type if the game object has one attached, null if it doesn't.

如果游戏物体有一个附加,则返回Type类型的组件,如果没有则为null。

C# users can use a generic version.

C#用户可以使用普通的版本。

  • C#

  • JavaScript

using UnityEngine;using System.Collections;public class example : MonoBehaviour {public Transform curTransform;void Start() {ExampleScript someScript;someScript = GetComponent<ExampleScript>();someScript.DoSomething();}public void Awake() {curTransform = GetComponent<Transform>();}}
// Equivalent to: Transform curTransform = transform;//等同于变换 curTransform = transformvar curTransform : Transform;curTransform = GetComponent (Transform);// You can access script components in the same way as other components.//你可以像其他组件一样访问脚本组件function Start () {var someScript : ExampleScript;someScript = GetComponent (ExampleScript);someScript.DoSomething ();}

• function GetComponent (type : string) : Component

Description描述

Returns the component with name type if the game object has one attached, null if it doesn't.

如果游戏物体有一个附加,则返回名字类型组件,如果没有则为null。

It is better to use GetComponent with a Type instead of a string for performance reasons.  Sometimes you might not be able to get to the type however, for example when trying to access a C# script from Javascript.  In that case you can simply access the component by name instead of type.  Example:

由于性能原因,最好使用Type的GetComponent,而不是用字符串。不过有时你可能无法得到Type,例如当你从Javascript访问C#脚本时,这个时候你可以简单通过名字而不是type来访问组件。例如:

  • C#

  • JavaScript

using UnityEngine;using System.Collections;public class example : MonoBehaviour {public ScriptName script;public void Awake() {script = GetComponent("ScriptName") as ScriptName;script.DoSomething();}}
// To access public variables and functions in another script attached to the same game object.//访问另一个脚本附加到一样的游戏物体的公共变量和函数var script : ScriptName;script = GetComponent("ScriptName");script.DoSomething ();


,