我的游戲中只有兩個場景。第一個是選單,第二個是游戲。在第二個場景中,我添加了背景音樂,并確保在重新加載場景時音樂不會中斷,但這意味著當回傳選單時,音樂會繼續與選單的音樂重疊。
你能給我任何解決方案嗎?謝謝!
這是使音樂隨著場景重新加載而繼續的代碼:
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);
}
}
}
uj5u.com熱心網友回復:
將相同的游戲物件與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.
}
}
如果您有任何問題,請在評論中告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/392536.html
