假设现在我们有两个游戏场景,一个是Home,一个是Game,现在来设置背景音乐。

1.创建节点
首先,在Home的场景中,创建一个空节点Audio,注意,这里必须是跟节点!

node.png
2.编写脚本
创建一个脚本AudioManager.js,
cc.Class({ extends: cc.Component, properties: { bgMusic:{ url:cc.AudioClip, default: null }, }, onLoad() { cc.game.addPersistRootNode(this.node); }, playBgMusic() { this.bgMusicChannel = cc.audioEngine.play(this.bgMusic,true,0.5) }, stopBgMusic: function () { if (this.bgMusicChannel !== undefined) { cc.audioEngine.stop(this.bgMusicChannel); this.bgMusicChannel = undefined; } }, });
我们在onLoad()方法中,将该节点设为常驻节点:
cc.game.addPersistRootNode(this.node);
此时该节点就可以在其他场景中获取到了
3.关联脚本
这一步就不用解释了吧,把该脚本挂载到Audio节点上
4.获取节点
在对应的场景脚本中,获取该常驻节点,调用播放音乐的方法即可
//获取全局播放器 this.AudioPlayer = cc.find("Audio").getComponent("AudioManager"); //停止再开启背景音乐 this.AudioPlayer.stopBgMusic(); this.AudioPlayer.playBgMusic();
转载: https://www.jianshu.com/p/2c0aaa434b44
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步