gpt4 book ai didi

c# - 在 Unity 中,如果在 IF 条件下找到组件,请立即使用它

转载 作者:行者123 更新时间:2023-12-05 00:45:55 25 4
gpt4 key购买 nike

我见过“如果在 IF 条件中找到组件,则使用它”的简写形式

所以而不是这个

SomeScript script = gameObject.GetComponent<SomeScript>();

if (script != null) {
script.DoSomething();
}

我见过这样的速记

if (SomeScript script = gameObject.GetComponent<SomeScript>()) {
script.DoSomething();
}

有人知道我的意思吗?很抱歉不知道术语

最佳答案

您很可能正在寻找(最近添加,我认为从 2019.2 及更高版本开始)TryGetComponent

来自 unity docs :

Gets the component of the specified type, if it exists.

TryGetComponent will attempt 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(out HingeJoint hinge))
{
hinge.useSpring = false;
}
}
}

或者使用你的例子

if (TryGetComponent(out SomeScript script)) 
{
script.DoSomething();
}

如果使用 TryGetComponent 找到组件,则对找到的组件的引用将存储在 out parameter 中。 ,然后您可以在 if block 内使用。

如果没有找到匹配的组件,则转到 else 部分。

关于c# - 在 Unity 中,如果在 IF 条件下找到组件,请立即使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62416752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com