如何切換場景不中斷音樂?

做法相當簡單,只要在Audio Source上掛上一個 DontDestroyOnLoad就可以了。

我自己是這樣做:

1.先建立要撥放音樂檔的prefab (建立prefab時放在場景上的記得刪除,不然會重複撥放。)

1624954970959

2.幫prefab設立Tag,取名為Sound(你要取其他的也可以啦XD)

1624955462870

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上,所有你需要的場景都要掛上哦),切換時音樂就不會中斷囉!

 

以上有任何問題歡迎提出,能幫忙我會幫忙的~

arrow
arrow
    文章標籤
    Unity C#
    全站熱搜
    創作者介紹
    創作者 黑羽 的頭像
    黑羽

    黑羽的小屋

    黑羽 發表在 痞客邦 留言(0) 人氣()