import { sys } from "cc"; import { oops } from "../../../../extensions/oops-plugin-framework/assets/core/Oops"; // AdManager.ts export class AdManager { private static instance: AdManager; // 微信和抖音的激励视频广告对象 private rewardVideoAd: any = null; // 广告单元ID,请替换为你的实际广告单元ID private adUnitId: string = 'adunit-d8e3c2b4bcfdc32e'; private dyAdUnitId: string = '3620da76lobm18tpb5' private isCanShow = true; private constructor() { } // 获取AdManager的单例对象 public static getInstance(): AdManager { if (!AdManager.instance) { AdManager.instance = new AdManager(); } return AdManager.instance; } // 初始化激励视频广告 public initRewardVideoAd() { if (sys.platform === sys.Platform.WECHAT_GAME) { // 微信小游戏环境 this.rewardVideoAd = wx.createRewardedVideoAd({ adUnitId: this.adUnitId }); this.rewardVideoAd.onError(err => { console.error('RewardedVideoAd Error: ', err); }); } else if (sys.platform === sys.Platform.BYTEDANCE_MINI_GAME) { // 抖音小游戏环境 this.rewardVideoAd = tt.createRewardedVideoAd({ adUnitId: this.dyAdUnitId }); this.rewardVideoAd.onError(err => { console.error('RewardedVideoAd Error: ', err); }); } } // 显示激励视频广告 public showRewardVideoAd(successCallback?: () => void, failCallback?: (err: any) => void) { if (!this.isCanShow) { oops.gui.toast('点击得太快了哟') return; } this.isCanShow = false; if (this.rewardVideoAd) { this.rewardVideoAd.show().then(() => { console.log('Rewarded video ad displayed!'); // successCallback && successCallback(); }).catch(err => { console.error('Failed to display rewarded video ad:', err); this.rewardVideoAd.load().then(() => this.rewardVideoAd.show()); failCallback && failCallback(err); failCallback = null oops.audio.resumeAll() }); // 监听广告关闭事件 this.rewardVideoAd.onClose((res: any) => { // 用户观看完整广告 if (res && res.isEnded) { console.log('Rewarded video ad watched till the end'); successCallback && successCallback(); successCallback = null oops.audio.resumeAll() } else { // 用户提前关闭广告 console.log('Rewarded video ad was closed before completion'); failCallback && failCallback(new Error('Ad was closed before completion')); failCallback = null oops.audio.resumeAll() } }); } else { console.error('Reward video ad is not initialized.'); failCallback && failCallback(new Error('Reward video ad is not initialized')); failCallback = null // successCallback && successCallback(); oops.audio.resumeAll() } // 0.5秒后重新开启按钮点击 const timer = setTimeout(() => { this.isCanShow = true; clearTimeout(timer) }, 1500); } }