GameObject.GetComponent
function GetComponent (type : Type) : Component
描述
返回游戏对象(gameObject)中附着的元件的类型(component of Type),如果没有附着,则返回一个Null。你可以通过内建元件或者带有这个功能的脚本来访问。
GetComponent是访问其他元件的主要方法。在Javascript脚本中,这种脚本的类型总是在项目视图中所看到的脚本的名称。
示例:
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Start() {
Transform curTransform;
curTransform = gameObject.GetComponent<Transform>();
curTransform = gameObject.transform;
}
void Update() {
ScriptName other = gameObject.GetComponent<ScriptName>();
other.DoSomething();
other.someVariable = 5;
}
}
function GetComponent (type : string) : Component
描述
返回游戏对象(gameObject)中所附着的元件的名称(the component with name type),如果没有附着,则返回一个Null。
以为性能的缘故,最好使用GetComponent来获取元件类型,而不是元件名称。有时候,你可能不需要获取类型,比如当你试图从Javascript脚本中去访问C#脚本。这种情况下,你可以简单的通过名称访问元件,而不是通过类型。
示例:
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Update() {
ScriptName other;
other = gameObject.GetComponent("ScriptName") as ScriptName;
other.DoSomething();
other.someVariable = 5;
}
}
分类: 游戏开发