当前位置: 首页 > article >正文

Unity游戏项目接广告

Unity游戏项目中接入GoogleAdMob

先看效果图

接入测试横幅广告,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using System;

public class GoogleAdMobManager : MonoBehaviour
{
    private static GoogleAdMobManager _instance;  

     public static GoogleAdMobManager Instance  
    {  
        get  
        {  
            if (_instance == null)  
            {  
                // 尝试在场景中找到GoogleAdMobManager实例  
                _instance = FindObjectOfType<GoogleAdMobManager>();  
  
                if (_instance == null)  
                {  
                    Debug.LogError("GoogleAdMobManager instance not found in the scene!");  
                }  
            }  
            return _instance;  
        }  
    }  

    private void Awake()  
    {  
        // 确保不会创建GoogleAdMobManager的多个实例  
        if (_instance != null && _instance != this)  
        {  
            Destroy(gameObject);  
            return;  
        }  
          
        _instance = this;  
        DontDestroyOnLoad(gameObject); // 防止在加载新场景时销毁此对象(可选)  
    }  

    void Start()
    {
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            CreateBannerView();  
            LoadAd();  
            ListenToAdEvents(); 

            // LoadInterstitialAd();           
          
        });
    }

    // Update is called once per frame
    void Update()
    {
        
    }


    #if UNITY_ANDROID
  private string _adUnitId = "ca-app-pub-3940256099942544/6300978111";
#elif UNITY_IPHONE
  private string _adUnitId = "ca-app-pub-3940256099942544/2934735716";
#else
  private string _adUnitId = "unused";
#endif

  BannerView _bannerView;

  /// <summary>
  /// Creates a 320x50 banner view at top of the screen.
  /// </summary>
  public void CreateBannerView()
  {
      Debug.Log("Creating banner view");

      // If we already have a banner, destroy the old one.
      if (_bannerView != null)
      {
          DestroyBannerView();
      }

      // Create a 320x50 banner at top of the screen
      _bannerView = new BannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
  }

  public void LoadAd()
{
    // create an instance of a banner view first.
    if(_bannerView == null)
    {
        CreateBannerView();
    }

    // create our request used to load the ad.
    var adRequest = new AdRequest();

    // send the request to load the ad.
    Debug.Log("Loading banner ad.");
    _bannerView.LoadAd(adRequest);
}

private void ListenToAdEvents()
{
    // Raised when an ad is loaded into the banner view.
    _bannerView.OnBannerAdLoaded += () =>
    {
        Debug.Log("Banner view loaded an ad with response : "
            + _bannerView.GetResponseInfo());
    };
    // Raised when an ad fails to load into the banner view.
    _bannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
    {
        Debug.LogError("Banner view failed to load an ad with error : "
            + error);
    };
    // Raised when the ad is estimated to have earned money.
    _bannerView.OnAdPaid += (AdValue adValue) =>
    {
        Debug.Log(String.Format("Banner view paid {0} {1}.",
            adValue.Value,
            adValue.CurrencyCode));
    };
    // Raised when an impression is recorded for an ad.
    _bannerView.OnAdImpressionRecorded += () =>
    {
        Debug.Log("Banner view recorded an impression.");
    };
    // Raised when a click is recorded for an ad.
    _bannerView.OnAdClicked += () =>
    {
        Debug.Log("Banner view was clicked.");
    };
    // Raised when an ad opened full screen content.
    _bannerView.OnAdFullScreenContentOpened += () =>
    {
        Debug.Log("Banner view full screen content opened.");
    };
    // Raised when the ad closed full screen content.
    _bannerView.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Banner view full screen content closed.");
    };
}

public void DestroyBannerView()
{
    if (_bannerView != null)
    {
        Debug.Log("Destroying banner view.");
        _bannerView.Destroy();
        _bannerView = null;
    }
}


}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using GoogleMobileAds.Api;


public class GameMgr : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void OnPlayButtonClick()
    {           
       SceneManager.LoadScene("02-Play");     
       GoogleAdMobManager.Instance?.DestroyBannerView(); 
       
    }

    public void JumpButtonClick()
    {           
       SceneManager.LoadScene("03-RewardAd");     
       
       
    }

    public void OnPauseButtonClick()
    {
        //暂停广告
        //展示广告
        LoadInterstitialAd();
    }

    private InterstitialAd _interstitialAd;  
    private  string _adUnitId = "ca-app-pub-3940256099942544/1033173712";
    
   
    public void LoadInterstitialAd()
    {
        if (_interstitialAd != null)
      {
            _interstitialAd.Destroy();
            _interstitialAd = null;
      } 
        Debug.Log("Loading the interstitial ad.");

    
       // InterstitialAd ad = new interstitialAd(_adUnitId);
        AdRequest adRequest = new AdRequest();

        InterstitialAd.Load(_adUnitId, adRequest,
          (InterstitialAd ad, LoadAdError error) =>
          {
              // if error is not null, the load request failed.
              if (error != null || ad == null)
              {
                  Debug.LogError("interstitial ad failed to load an ad " +
                                 "with error : " + error);
                  return;
              }

              Debug.Log("Interstitial ad loaded with response : "
                        + ad.GetResponseInfo());

              _interstitialAd = ad;
          });

          ShowInterstitialAd();

    }


    public void ShowInterstitialAd()
{
    if (_interstitialAd != null && _interstitialAd.CanShowAd())
    {
        Debug.Log("Showing interstitial ad.");
        _interstitialAd.Show();
    }
    else
    {
        Debug.LogError("Interstitial ad is not ready yet.");
    }
}

}

场景1,MainCamera上挂载上面两个脚本,GoogleAdMobManager .cs和 GameMgr.cs

创建StartButton按钮

场景2,加载插屏广告InterstitialAd,Main Camera上挂载Game Mgr.cs

创建Pause Game按钮,当暂停的时候,显示插屏广告,调用Game Mgr.cs中OnPauseButtonClick()方法

创建Jump to reward ad,点击跳转到激励广告。点击JumpButton触发GameMgr中JumpButtonClick()方法。

场景2,02-play中的Main Camera上的Audio Listener需去除,项目场景中只能有一个Audio Listener

场景3,加载激励广告

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using GoogleMobileAds.Api;
using System;

public class RewardAd : MonoBehaviour
{
    

    #if UNITY_ANDROID
        private string _adUnitId = "ca-app-pub-3940256099942544/5224354917";
    #elif UNITY_IPHONE
        private string _adUnitId = "ca-app-pub-3940256099942544/1712485313";
    #else
        private string _adUnitId = "unused";
    #endif

  private RewardedAd _rewardedAd;



    void Start()
    {
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            LoadRewardedAd();
            
        });
        
    }



    public void LoadRewardedAd()
    {
        // Clean up the old ad before loading a new one.
        if (_rewardedAd != null)
        {
                _rewardedAd.Destroy();
                _rewardedAd = null;
        }

        Debug.Log("Loading the rewarded ad.");

        // create our request used to load the ad.
        var adRequest = new AdRequest();

        // send the request to load the ad.
        RewardedAd.Load(_adUnitId, adRequest,
            (RewardedAd ad, LoadAdError error) =>
            {
                // if error is not null, the load request failed.
                if (error != null || ad == null)
                {
                    Debug.LogError("Rewarded ad failed to load an ad " +
                                    "with error : " + error);
                    return;
                }

                Debug.Log("Rewarded ad loaded with response : "
                            + ad.GetResponseInfo());

                _rewardedAd = ad;
            });

            ShowRewardedAd();
    }

public void ShowRewardedAd()
{
    const string rewardMsg =
        "Rewarded ad rewarded the user. Type: {0}, amount: {1}.";

    if (_rewardedAd != null && _rewardedAd.CanShowAd())
    {
        _rewardedAd.Show((Reward reward) =>
        {
            // TODO: Reward the user.
            Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
        });
    }
}

public void DestroyRewardedAd()
{
    if (_rewardedAd != null)
    {
        Debug.Log("Destroying rewardedAd view.");
        _rewardedAd.Destroy();
        _rewardedAd = null;
    }
}



}


http://www.kler.cn/a/272568.html

相关文章:

  • Linux 操作二:文件映射与文件状态
  • 使用 Java 开发 Android 应用:Kotlin 与 Java 的混合编程
  • 简历_基于 Cache Aside 模式解决数据库与缓存一致性问题。
  • 【蜂巢——方向,数学】
  • 西门子【Library of Basic Controls (LBC)基本控制库”(LBC) 提供基本控制功能】
  • ThinkPhp项目解决静态资源请求的跨域问题的解决思路
  • 航空公司遭遇Play恶意家族攻击,亚信安全发布《勒索家族和勒索事件监控报告》
  • mudo服务器测试一
  • 关于MySQL数据库的学习3
  • 【深度学习】diffusers 学习过程记录,StableDiffusion扩散原理
  • 海豚调度系列之:认识海豚调度
  • Git一点通
  • lua profile 性能分析工具都有哪些
  • ISIS多区域实验简述
  • Vue工程化基础
  • Debug追踪
  • LeetCode 热题100专题解析:哈希与双指针
  • 【力扣白嫖日记】262.行程和用户
  • 《深入解析 C#》—— C# 2 部分
  • SAP ABAP read table 时关键字TRANSPORTING NO FIELDS的用法
  • 如何用shell脚本构建Android模块
  • 整型溢出问题及解决之道
  • 一直出现问题,发现服务器磁盘空间已满导致,腾出服务器磁盘空间命令
  • 【Linux下qt软件安装打包附带问题: dpkg: error processing package xxxx +解决方式+自我尝试+记录】
  • 深度学习pytorch——Tensor维度变换(持续更新)
  • Linux怎么查看当前进程?怎么执行退出?怎么查看当前路径?