首页 > 解决方案 > 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);
 }

}

现在请给我一些建议来解决这个问题。

标签: unity3d

解决方案


您在尝试播放声音的脚本中引用了您正在销毁的 AudioManager。

这样想吧。你有

AudioManager A - DontDestroyOnLoad

AudioManager B - 因为 A 存在而被破坏

在您的脚本中,您在首次启动时引用了 AudioManager A。然后,当您离开场景并返回时,您现在正在引用 AudioManager B,因为 A 存在而被破坏。您需要做的就是始终引用 AudioManager A,而不是 B。


推荐阅读