NO.49-------Unity播放背景音乐不受场景切换影响

本文介绍了一种在Unity中实现跨场景音乐连续播放的方法,通过使用don't destory on load功能保持音频源不被销毁,并在摄像机上挂载音乐播放组件确保音乐在场景切换时无缝衔接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理就是在场景中放置一个预制体,设置标签为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 () {
		
	}
}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值