public Component GetComponent (Type type);

参数

type要检索的组件的类型。

描述

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

GetComponent 是访问其他组件的主要方式。在 javascript 中,脚本的类型始终为项目视图中所看到的脚本名称。您可以使用此函数访问内置组件或脚本。

using UnityEngine;

public class GetComponentExample : MonoBehaviour { void Start() { HingeJoint hinge = gameObject.GetComponent(typeof(HingeJoint)) as HingeJoint;

if (hinge != null) hinge.useSpring = false; } }

public T GetComponent ();

描述

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

using UnityEngine;

public class GetComponentGenericExample : MonoBehaviour { void Start() { HingeJoint hinge = gameObject.GetComponent<HingeJoint>();

if (hinge != null) hinge.useSpring = false; } }

public Component GetComponent (string type);

参数

type要检索的组件的类型。

描述

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

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

using UnityEngine;

public class GetComponentNonPerformantExample : MonoBehaviour { void Start() { HingeJoint hinge = gameObject.GetComponent("HingeJoint") as HingeJoint;

if (hinge != null) hinge.useSpring = false; } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961