public Component GetComponent (Type type);

参数

type要检索的组件的类型。

描述

如果游戏对象附加了类型为 type 的组件,则将其返回,否则返回 null。

using UnityEngine;

public class ScriptExample : MonoBehaviour { void Start() { // Disable the spring on the HingeJoint component. HingeJoint hinge = GetComponent<HingeJoint>(); hinge.useSpring = false; } }

public T GetComponent ();

描述

通用版本。有关更多详细信息,请参阅通用函数页面。


public Component GetComponent (string type);

描述

如果游戏对象附加了名为 type 的组件,则将其返回,否则返回 null。

出于性能原因,最好使用具有 Type 而不是字符串的 GetComponent。 但有时可能无法访问该类型,例如在尝试从 Javascript 访问 C# 脚本时。 在这种情况下,可以仅根据名称而不是类型访问该组件。 示例:

using UnityEngine;

public class ScriptExample : MonoBehaviour { void Start() { // Disable the spring on the HingeJoint component. HingeJoint hinge = GetComponent("HingeJoint") as HingeJoint; hinge.useSpring = false; } }