【发布时间】:2016-05-31 11:25:45
【问题描述】:
我目前在 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-coalessing 运算符将null 分配给specifiedUISound,即使它为null 而audioUIManager 的声音不是。另外,如果我使用三元运算符来检查 null ,我可以让它工作,如下所示:
specifiedUISound = specifiedUIsound == null ? audioUIManager.genericUISound : specifiedUISound;
我是否误解了 null 合并运算符?为什么会这样?
编辑: Jerry Switalski 指出,这只发生在specifiedUISound 被序列化时。 (如果它是public 或者如果它具有[SerializeField] 属性)。谁能解释一下这里发生了什么?
【问题讨论】:
-
s = s ?? “测试”;在这里工作正常
-
所以你是说
foo = foo ?? bar不起作用,但foo = foo == null ? bar : foo起作用? Unity 没有改变 C# 规则,所以它一定是你的代码。您是否可能在创建minimal reproducible example 时走得太远,以至于您删除了太多相关代码?AudioClip是什么类型,是struct还是class? -
是的,我测试了这个例子,它重现了问题。如果您创建这两个类并将它们统一添加到两个不同的游戏对象中,那么它会重新创建它!如果我不以这种方式使用它,它可以正常工作。
-
我相信
audioUIManager.genericUISound是null,而代码正在执行,并且稍后才会变为非空。您是否调试过这种情况并实际看到了这种行为?请在代码执行前输出audioUIManager.genericUISound的值。 -
@NineBerry 刚刚检查过,
audioUIManager.genericUISound事先不为空。此外,带有三元运算符的方法如果为 null 也将不起作用。
标签: c# serialization unity3d null null-coalescing-operator