有很多按钮需要加音效,如何做到全局通用而不是一个个的在按钮内部增加音效播放?

有很多按钮需要加音效,如何做到全局通用而不是一个个的在按钮内部增加音效播放?

1赞

搞一个自定义按钮组件吧 继承自 cc.Button 重写按钮的点击事件 加上通用音效 然后再往下分发 各自处理各自的逻辑

cc.Class({
extends: cc.Button,
properties: {
clip: {
default: null,
url: cc.AudioClip
},
},
_onTouchEnded: function (event) {
if (!this.interactable || !this.enabledInHierarchy) return;

             if (this._pressed) {
                 cc.audioEngine.play(this.clip, false, 1);
                 cc.Component.EventHandler.emitEvents(this.clickEvents, event);
                 this.node.emit('click', this);
             }
             this._pressed = false;
             this._updateState();
             event.stopPropagation();
         },
     });

没太理解。

let oldFun: Function = Button.prototype[’_onTouchEnded’];

let newFun: Function = function (event) {

oldFun.apply(this, [event]);

AudioManager.getInstance().playEffect("anniu");

}

Button.prototype[’_onTouchEnded’] = newFun;

properties: {
clickSound: {
default: null,
type: cc.AudioClip
},
callback: {
default: null,
type: cc.Component.EventHandler
}
},

_onTouchEnded(event) {
    if (this.clickSound) {
        cc.audioEngine.playEffect(this.clickSound, false);
    }
    if (this.callback) {
        this.callback.emit([event]);
    }
    this._super(event);
}

/**[XuanYou]

 * 一键添加按钮音效

 * @param bundle 音效分包

 * @param url 音效路径

 * @returns

 */

static AddButtonSound(bundle: string, url: string) {

    cc.Button.prototype["touchBeganClone"] = cc.Button.prototype["_onTouchEnded"];

    cc.Button.prototype["_onTouchEnded"] = function (event) {

        if (this.interactable && this.enabledInHierarchy) {

            // 播放自己的按钮音效

            AudioMgr.SoundPlay(bundle, url);

        }

        this.touchBeganClone(event);

    }

}

放在哪里呢?

写一个节点监听事件,这个节点被点击的时候判断一下是否是按钮,是按钮播放music