原理就是在场景中放置一个预制体,设置标签为sound,挂载audio source组件,同时挂载一个场景切换时自身不会销毁的脚本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class dontdestroyme : MonoBehaviour {
// Use this for initialization
void Start () {
DontDestroyOnLoad(this.gameObject);
}
// Update is called once per frame
void Update () {
}
}
另外在摄像机上挂载一个音乐播放组件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bgsound : MonoBehaviour {
public GameObject obje;
GameObject obj=null;
// Use this for initialization
// Use this for initialization
void Start () {
obj = GameObject.FindGameObjectWithTag("sound");
if (obj==null) {
obj = (GameObject)Instantiate(obje); }
}
// Update is called once per frame
void Update () {
}
}