Unity-在游戏中添加背景音乐

Rak*_*ama 0 c# unity-game-engine

我想在游戏中添加一些可以在每个场景中播放的音乐,如果场景改变了,音乐也不会再次开始,可以在设置菜单上将其关闭

有人可以帮我弄清楚吗?

小智 6

你试过什么了?显示您的代码。有一种方法可以实现您想要的功能,即使用DontDestroyOnLoad功能。创建一个gameObject,添加AudioSource到其中,然后将以下脚本添加到该gameObject中:

public class AudioPlayerManager: MonoBehaviour
{
      private static AudioPlayerManager instance = null;
      private AudioSource audio;

      private void Awake()
      {
          if (instance == null)
          { 
               instance = this;
               DontDestroyOnLoad(gameObject);
               return;
          }
          if (instance == this) return; 
          Destroy(gameObject);
      }

      void Start()
      {
         audio = GetComponent<AudioSource>();
         audio.Play();
      }
}
Run Code Online (Sandbox Code Playgroud)