简体   繁体   English

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

[英]Unity - Add Background Music on Game

I want to add some music in my game that can play in every scene, and if scenes change music doesn't start again and can be turn off on setting menu 我想在游戏中添加一些可以在每个场景中播放的音乐,如果场景改变了,音乐也不会再次开始,可以在设置菜单上将其关闭

can someone help me to figure it out? 有人可以帮我弄清楚吗?

What have you tried so far? 你试过什么了? Show your code. 显示您的代码。 There is a way to achieve what you want, that is by using DontDestroyOnLoad function. 有一种方法可以实现您想要的,即使用DontDestroyOnLoad函数。 Create a gameObject, add AudioSource to it and then add the below script to that gameObject: 创建一个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();
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM