posts - 320,  comments - 29,  views - 115万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

假设现在我们有两个游戏场景,一个是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

posted on   刘世涛6192  阅读(148)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示