AdManager.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { sys } from "cc";
  2. // AdManager.ts
  3. export class AdManager {
  4. private static instance: AdManager;
  5. // 微信和抖音的激励视频广告对象
  6. private rewardVideoAd: any = null;
  7. // 广告单元ID,请替换为你的实际广告单元ID
  8. private adUnitId: string = 'adunit-d8e3c2b4bcfdc32e';
  9. private constructor() {}
  10. // 获取AdManager的单例对象
  11. public static getInstance(): AdManager {
  12. if (!AdManager.instance) {
  13. AdManager.instance = new AdManager();
  14. }
  15. return AdManager.instance;
  16. }
  17. // 初始化激励视频广告
  18. public initRewardVideoAd() {
  19. if (sys.platform === sys.Platform.WECHAT_GAME) {
  20. // 微信小游戏环境
  21. this.rewardVideoAd = wx.createRewardedVideoAd({ adUnitId: this.adUnitId });
  22. this.rewardVideoAd.onError(err => {
  23. console.error('RewardedVideoAd Error: ', err);
  24. });
  25. } else if (sys.platform === sys.Platform.BYTEDANCE_MINI_GAME) {
  26. // 抖音小游戏环境
  27. this.rewardVideoAd = tt.createRewardedVideoAd({ adUnitId: this.adUnitId });
  28. this.rewardVideoAd.onError(err => {
  29. console.error('RewardedVideoAd Error: ', err);
  30. });
  31. }
  32. }
  33. // 显示激励视频广告
  34. public showRewardVideoAd(successCallback?: () => void, failCallback?: (err: any) => void) {
  35. if (this.rewardVideoAd) {
  36. this.rewardVideoAd.show().then(() => {
  37. console.log('Rewarded video ad displayed!');
  38. successCallback && successCallback();
  39. }).catch(err => {
  40. console.error('Failed to display rewarded video ad:', err);
  41. this.rewardVideoAd.load().then(() => this.rewardVideoAd.show());
  42. failCallback && failCallback(err);
  43. });
  44. // 监听广告关闭事件
  45. this.rewardVideoAd.onClose((res: any) => {
  46. // 用户观看完整广告
  47. if (res && res.isEnded) {
  48. console.log('Rewarded video ad watched till the end');
  49. successCallback && successCallback();
  50. } else {
  51. // 用户提前关闭广告
  52. console.log('Rewarded video ad was closed before completion');
  53. failCallback && failCallback(new Error('Ad was closed before completion'));
  54. }
  55. });
  56. } else {
  57. console.error('Reward video ad is not initialized.');
  58. failCallback && failCallback(new Error('Reward video ad is not initialized'));
  59. }
  60. }
  61. }