提问人:Jahill 提问时间:1/11/2023 更新时间:1/11/2023 访问量:38
在Unity中使用组件进行短路评估
Short Circuit Evaluation with Components in Unity
问:
我有一行代码:游戏对象在哪里。当我尝试使用短路评估来简化这一点时,它给出了错误。Rigidbody rigidbody = go.GetComponent<Rigidbody>() ? go.GetComponent<Rigidbody>() : go.AddComponent(typeof(Rigidbody)) as Rigidbody;
go
Rigidbody rigidbody = go.GetComponent<Rigidbody>() || go.AddComponent(typeof(Rigidbody)) as Rigidbody;
CS0029: Cannot implicitly convert type 'bool' to 'UnityEngine.Rigidbody'
我在这里做短路评估是否不正确?是否可以使用短路来做到这一点,或者我必须使用更长的解决方案。
任何帮助或建议都是值得赞赏的。谢谢。
答:
0赞
Jahill
1/11/2023
#1
好的,所以我忘记了空合并,这正是我正在寻找的解决方案。我的思绪停留在 JavaScript 上,其中短路评估的作用类似于 null 合并,但 C# 没有这样的概念。
从本质上讲,我的问题是使用而不是.||
??
评论
1赞
hijinxbassist
1/11/2023
避免在 unity 对象上使用 null 合并运算符,因为它并不总是提供所需的值。这是由于 Object 的相等运算符的 unity 覆盖。Object 的引用清楚地说明了这一点:This class doesn't support the null-conditional operator (?.) and the null-coalescing operator (??).
1赞
Milan Egon Votrubec
1/11/2023
#2
您在此处描述的场景是 Unity 也提供 .TryGetComponent<T>(out T component)
你可以这样使用它:
if ( !go.TryGetComponent<Rigidbody>( out var rigidbody ) )
rigidbody = go.AddComponent<Rigidbody>() as Rigidbody;
// rigidbody is now set ...
这样可以防止 Unity 对象在某些情况下显示为非 null 的怪癖,并满足 Unity 工程师要求您不使用 null 条件/合并运算符的要求。
评论