GameObject.GetComponent
GetComponent(type: Type): Component;
Parameters
| type | The type of Component to retrieve. |
Description
Returns the component of Type type if the game object has one attached, null if it doesn't. You can access both builtin components or scripts with this function.
GetComponent is the primary way of accessing other components. From javascript the type of a script is always the name of the script as seen in the project view. Example:
GetComponent的主要方式是访问其他组件。从javascript脚本的类型总是脚本的名称作为项目视图中看到。示例:
function Start () {
var curTransform : Transform;
curTransform = gameObject.GetComponent(Transform);
// This is equivalent to:
curTransform = gameObject.transform;
} function Update () {
// To access public variables and functions
// in another script attached to the same game object.
// (ScriptName is the name of the javascript file)
var other : ScriptName = gameObject.GetComponent(ScriptName);
// Call the function DoSomething on the script
other.DoSomething ();
// set another variable in the other script instance
other.someVariable = 5;
}
GetComponent(): T;
Description
Generic version. See the Generic Functions page for more details.
GetComponent(type: string): Component;
Parameters
| type | The type of Component to retrieve. |
Description
Returns the component with name type if the game object has one attached, null if it doesn't.
返回组件名称类型如果游戏对象有一个附件,空如果它不。
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:
最好是使用GetComponent类型而不是一个字符串由于性能的原因。有时候你可能无法到达类型然而,例如当试图访问一个c#脚本从Javascript。在这种情况下你可以直接访问组件的名字相反的类型。示例:
function Update () {
// To access public variables and functions
// in another script attached to the same game object.
// (ScriptName is the name of the javascript file)
var other : ScriptName;
other = gameObject.GetComponent("ScriptName");
// Call the function DoSomething on the script
other.DoSomething ();
// set another variable in the other script instance
other.someVariable = 5;
}
本文介绍了Unity游戏开发中如何使用GetComponent方法来获取GameObject上的组件。文章详细解释了该方法的不同用法及其参数,并通过示例展示了如何从JavaScript脚本中访问附加到同一游戏对象上的其他脚本。
3903

被折叠的 条评论
为什么被折叠?



