如何切換場景不中斷音樂?
做法相當簡單,只要在Audio Source上掛上一個 DontDestroyOnLoad就可以了。
我自己是這樣做:
1.先建立要撥放音樂檔的prefab (建立prefab時放在場景上的記得刪除,不然會重複撥放。)
2.幫prefab設立Tag,取名為Sound(你要取其他的也可以啦XD)
3.在prefab中掛上C# script,內容如下:
------------------------------
using UnityEngine;
public class DontDestroyMe : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
DontDestroyOnLoad(this.gameObject);
}
// Update is called once per frame
void Update()
{
}
}
------------------------------
這個內容主要是讓音樂檔不會在切換scene時被銷毀。
4.建立第二個C# script,內容如下:
------------------------------
using UnityEngine;
public class BackGroundMusic : MonoBehaviour
{
public GameObject TitleBGM;
GameObject BGM = null;
// Start is called before the first frame update
void Start()
{
BGM = GameObject.FindGameObjectWithTag("Sound");
if (BGM == null)
{
BGM = Instantiate(TitleBGM);
}
}
// Update is called once per frame
void Update()
{
}
}
------------------------------
這個內容主要是檢查目前的場景中有沒有Tag是Sound的物件(也就是我們的音樂檔),
若沒有,則新增一個音樂檔到場景中,
若有,則不做任何動作。
將此C# script掛在你想切換的場景中(我個人掛在Main Carema上,所有你需要的場景都要掛上哦),切換時音樂就不會中斷囉!
以上有任何問題歡迎提出,能幫忙我會幫忙的~
留言列表