type | 要检索的组件的类型。 |
Returns the component of Type type
if the GameObject has one attached, null if it doesn't.
使用 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; } }
Generic version of this method.
using UnityEngine;
public class GetComponentGenericExample : MonoBehaviour { void Start() { HingeJoint hinge = gameObject.GetComponent<HingeJoint>();
if (hinge != null) hinge.useSpring = false; } }
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; } }