Version: 2021.3
public Component GetComponent (Type type);

参数

type 要检索的组件的类型。

描述

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

使用 gameObject.GetComponent 将返回找到的第一个组件,并且未定义顺序。如果预期存在多个相同类型的组件,请改用 gameObject.GetComponents,并针对某些唯一的属性循环使用返回的组件测试。

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 ();

描述

Generic version of this method.

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 要检索的组件的类型。

描述

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

To improve the performance of your code, use GetComponent with a type instead of a string.

using UnityEngine;

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

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