Version: 2020.1

GameObject.TryGetComponent

切换到手册

参数

type 要获取的组件的类型。
component 输出参数将包含组件或 /null/。

返回

bool 如果发现组件,则返回 /true/,否则返回 /false/。

描述

获取指定类型的组件(如果存在)。

TryGetComponent 将尝试获取给定类型的组件。与 GameObject.GetComponent 相比的显著差异在于,如果请求的组件不存在,则此方法不在编辑器中进行分配。

using UnityEngine;

public class TryGetComponentExample : MonoBehaviour { void Start() { if (gameObject.TryGetComponent(typeof(HingeJoint), out Component component)) { component.name = "My Hinge"; } } }

public bool TryGetComponent (out T component);

参数

component 输出参数将包含组件或 /null/。

返回

bool 如果发现组件,则返回 /true/,否则返回 /false/。

描述

Generic version of this method.

using UnityEngine;

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