Version: 2023.2

Component.TryGetComponent

切换到手册
public bool TryGetComponent (out T component);

参数

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

返回

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

描述

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

TryGetComponent attempts to retrieve the component of the given type. The notable difference compared to GameObject.GetComponent is that this method does not allocate in the Editor when the requested component does not exist.

using UnityEngine;

public class TryGetComponentExample : MonoBehaviour { void Start() { if (TryGetComponent<HingeJoint>(out HingeJoint hinge)) { hinge.useSpring = false; } } }

public bool TryGetComponent (Type type, out Component component);

参数

type The type of component to search for.
component 输出参数将包含组件或 /null/。

返回

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

描述

The non-generic version of this method.

This version of TryGetComponent is not as efficient as the Generic version (above), so you should only use it if necessary.