unity3d - DontDestroyOnLoad GameObject 上 AudioSource 中的 MissingReferenceException
问题描述
当我更改游戏场景并再次移回同一场景时,我的音频源中出现缺少参考异常。
在我更改主菜单场景之前,它工作正常,但在更改并移回主菜单场景后,它开始显示此异常。
这是我为 AudioManager 编写的代码:
public class AudioManager : MonoBehaviour
{
static AudioManager instance;
//
[SerializeField] AudioClip buttonClickClip;
[SerializeField] AudioSource myAudioSource;
private void Awake()
{
instance = this;
}
public static AudioManager Instance
{
get
{
return instance;
}
}
public void PlayButtonClickSound()
{
if (GameManager.Instance.IsEnableSounds)
myAudioSource.PlayOneShot(buttonClickClip);
}
}
这是我为 DontDestroyOnLoad 编写的代码:
public class DontDetroyOnLoad : MonoBehaviour
{
private static bool created = false;
void Awake()
{
if (!created)
{
DontDestroyOnLoad(this.gameObject);
created = true;
}
else
Destroy(this.gameObject);
}
}
现在请给我一些建议来解决这个问题。
解决方案
您在尝试播放声音的脚本中引用了您正在销毁的 AudioManager。
这样想吧。你有
AudioManager A - DontDestroyOnLoad
AudioManager B - 因为 A 存在而被破坏
在您的脚本中,您在首次启动时引用了 AudioManager A。然后,当您离开场景并返回时,您现在正在引用 AudioManager B,因为 A 存在而被破坏。您需要做的就是始终引用 AudioManager A,而不是 B。
推荐阅读
- python - 如何在运行 .py 脚本的目录中创建文件?
- json - 在反应中传递道具 - 获取
- python-3.x - 如何将 python 脚本日志记录到在 Google Cloud VM 上运行的 Google Stackdriver 日志记录中
- javascript - getElementsByTagName 的替代方法并传递信息
- actionscript-3 - 如何在具有控制功能的动作脚本中创建拖放类,同时仍然是通用的?
- c++ - 新手:如何为 w7 安装(哪个)C++ 编译器?
- json - jstree hover_node 为 ToolTip 使用自定义数据
- python - 为分类算法绘制散点图
- javascript - IJavaScriptExecutor.ExecuteScript 等到 ajax 完成
- php - 解码 UTF8 的问题