gpt4 book ai didi

c# - 空合并运算符赋值给自己

转载 作者:太空狗 更新时间:2023-10-29 20:58:23 24 4
gpt4 key购买 nike

我目前在 Unity 中设置了两个脚本来处理一些 UI 音频。一个是管理器,另一个是为特定的 UI 元素播放声音。我所拥有的简化版本是这样的:

public class AudioUIManager : MonoBehaviour //Only one of these in the scene
{
public AudioClip genericUISound; //This is set in the inspector.
}

public class AudioUITextAnimation : MonoBehaviour
{
[SerializeField]
private AudioClip specifiedUISound; //This is not set in the inspector
[SerializeField]
private AudioUIManager audioUIManager; // I get a reference to this elsewhere

void Start()
{
//Use generic sounds from audio manager if nothing is specified.
specifiedUISound = specifiedUISound ?? audioUIManager.genericUISound;
print(specifiedUISound);
}
}

我在这里试图实现的是让 specifiedUISound 字段使用在检查器中分配给它的声音。如果未分配声音,则使用来自 UI 管理器的通用声音。这节省了我将相同的声音分配给数百万个需要相同声音的按钮,但如果我愿意,我可以选择为一个按钮提供特定的声音。

但是,空合并运算符正在将null 分配给specifiedUISound,即使它是null 并且audioUIManager 的声音不是。另外,如果我像这样使用三元运算符检查 null,我可以让它工作:

specifiedUISound = specifiedUIsound == null ? audioUIManager.genericUISound : specifiedUISound;

我是否误解了空合并运算符?为什么会这样?

编辑:Jerry Switalski 指出,只有当 specifiedUISound 被序列化时才会发生这种情况。 (如果它是 public 或者如果它有 [SerializeField] 属性)。任何人都可以阐明这里发生的事情吗?

最佳答案

您遇到了 Unity 的 custom equality operator :

When a MonoBehaviour has fields, in the editor only, we do not set those fields to “real null”, but to a “fake null” object. Our custom == operator is able to check if something is one of these fake null objects, and behaves accordingly. While this is an exotic setup, it allows us to store information in the fake null object that gives you more contextual information when you invoke a method on it, or when you ask the object for a property. Without this trick, you would only get a NullReferenceException, a stack trace, but you would have no idea which GameObject had the MonoBehaviour that had the field that was null.

在编辑器中运行时,Unity 将序列化的 null 替换为实际上不是 null 的标记值。这允许他们在某些情况下提供更多信息性错误消息。

specifiedUISound是否等于null?那要看你怎么问了。 C# 有多个“相等”概念,包括 data equality and reference equality .

有些检查会说值相等:==Object.Equals

其他人会说它们不相等:??Object.ReferenceEquals

此行为只会发生在编辑器中。在独立构建中运行时,任何 null 值都将只是 null

关于c# - 空合并运算符赋值给自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37544413/

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