如何将背景音乐从一个场景更改为另一个场景?

How can I change the background music from one scene to another?

我的游戏中只有两个场景。 第一个是菜单,第二个是游戏。 在第二个场景中,我添加了背景音乐,并确保在重新加载场景时音乐不会中断,但这意味着当返回菜单时,音乐会继续与菜单重叠。

你能给我一些解决方案吗?谢谢!

这是让音乐随着场景重新加载而继续播放的代码:

using UnityEngine;
using UnityEngine.SceneManagement;

public class BackgroundMusic : MonoBehaviour
{
    private static BackgroundMusic backgroundMusic;
    
    void Awake()
    {
    
       if (backgroundMusic == null)
        {
            backgroundMusic = this;
            DontDestroyOnLoad(backgroundMusic);
            Debug.Log(SceneManager.GetActiveScene().name);
        }
        else
        {
            Destroy(gameObject);
        }
    }

}

在两个场景中使用 BackgroundMusic 脚本放置相同的游戏对象。由于您实施了单例模式,这将确保一次只能播放 1 个音乐播放器。

现在,订阅SceneManager.sceneLoaded,这样您就可以根据场景更改音乐,例如:

using UnityEngine.SceneManagement;

public class BackgroundMusic : MonoBehaviour
{
    private static BackgroundMusic backgroundMusic;

    void Awake() 
    { 
        // Keep singleton pattern implementation here 
        SceneManager.onSceneLoaded += SwitchMusic;
    }

    void SwitchMusic()
    {
        // Logic to change music tracks here.
        // You could have an array of AudioClip and index 
        // that array by the scene's build index, for instance.

        // You can also just check if scenes actually changed, and if not,
        // you can make the music just continue without changing.
    }
}

如有任何问题,请在评论中告诉我。