Unity 背景音乐 跨场景播放

来源:互联网 发布:重新加载数据会丢吗 编辑:程序博客网 时间:2024/05/22 13:42

1、把添加了AudioSource(声音片段:背景音乐)和“Dont DestroyOnLoad”脚本的空物体,拖成预设体。(注意预设体tag要设成“sound”,第2步脚本里要用。)----可以给空物体取一个有意义的名字,如bgmPrefab。

using UnityEngine;
using System.Collections;


public class DontDestroyMybgm : MonoBehaviour {
    void Awake()
    {
      
    }
// Use this for initialization
void Start () {
        DontDestroyOnLoad(this.gameObject);
}

// Update is called once per frame
void Update () {

}
}


2、建Text.cs,加到每个场景任意物体上。

using UnityEngine;
using System.Collections;


public class Test : MonoBehaviour {
    public GameObject bgmPrefab;
    public GameObject bgmInstance = null;
// Use this for initialization
void Start () {
        bgmInstance= GameObject.FindGameObjectWithTag("sound");
        if (bgmInstance == null)
        {
            bgmInstance = (GameObject)Instantiate(bgmPrefab);
        }

}

// Update is called once per frame
void Update () {

}
}


3、把第1步建立的空物体去掉,以免出现声音重叠。


原创粉丝点击