R
R
ReWire_922019-04-21 18:40:49
C++ / C#
ReWire_92, 2019-04-21 18:40:49

Why aren't AdMob standard event handlers firing?

People, something is already not working for me at all (
Maybe you will see with a fresh mind what is wrong and why this code does not work?
At the very beginning of the script execution, I subscribe the standard events of the AdMob ad units to the corresponding ad units, handlers don't fire, code inside them doesn't execute What am I doing wrong?

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

public class GoogleADS : MonoBehaviour {

  public static GoogleADS Instance { get { return instance; } }
  private static GoogleADS instance;
  private const string bottomBanner = "ca-app-pub-3940256099942544/6300978111";
  private const string InterstitialId = "ca-app-pub-3940256099942544/1033173712";

  public static int ShowPersonalizedAds = 1;

  private static BannerView BottomAd;
  private static InterstitialAd IntAds;

  public bool AdsInitialized = false;

  void Awake(){
    if (GoogleADS.instance == null) {
      DontDestroyOnLoad (this);
      instance = this;
      Invoke ("InitializeAds", 1f);
    }

  }

  void InitializeAds(){
    MobileAds.Initialize ("ca-app-pub-3940256099942544~3347511713");
    PrepareBanner ();
    PrepareInterstitial ();
    AdsInitialized = true;
    Debug.Log("Ads initialized: " + AdsInitialized.ToString());

    BottomAd.OnAdLoaded += BannerLoaded;
    BottomAd.OnAdFailedToLoad += BannerFailedToLoad;

    IntAds.OnAdLoaded += InterstitialLoaded;
    IntAds.OnAdFailedToLoad += InterstitialFailedToLoad;
    IntAds.OnAdClosed += InterstitialClosed;
  }

  public static void CheckPersonalization(){
    if (PlayerPrefs.HasKey ("PersonalizedAds")) {
      ShowPersonalizedAds = PlayerPrefs.GetInt ("PersonalizedAds");
      if (ShowPersonalizedAds == 1) {
        Debug.Log ("Персонализированная реклама разрешена к показу");
      } else {
        Debug.Log ("Персонализированная реклама запрещена");
      }
    } else {
      ShowPersonalizedAds = 0;
      Debug.Log ("Персонализированная реклама запрещена");
    }
  }

  void PrepareBanner(){
    Debug.Log ("Banner: отправляем запрос на загрузку рекламы");
    BottomAd = new BannerView (bottomBanner, AdSize.SmartBanner, AdPosition.Bottom);

    AdRequest bannerRequest = new AdRequest.Builder ()
      .AddTestDevice (AdRequest.TestDeviceSimulator)
      .AddTestDevice (SystemInfo.deviceUniqueIdentifier.ToUpper())
      .Build ();
    BottomAd.LoadAd (bannerRequest);
  }

  void PrepareInterstitial(){
    Debug.Log("Interstitial: отправляем запрос на загрузку рекламы");
    IntAds = new InterstitialAd (InterstitialId);

    AdRequest intAdRequest = new AdRequest.Builder ()
      .AddTestDevice (AdRequest.TestDeviceSimulator)
      .AddTestDevice (SystemInfo.deviceUniqueIdentifier.ToUpper())
      .Build ();
    IntAds.LoadAd (intAdRequest);
  }

  public static void ShowInterstitial (){

    if (IntAds.IsLoaded ()) {
      IntAds.Show ();
      Debug.Log ("Interstitial: показываем рекламу");
    } else {
      Debug.LogWarning ("Interstitial: реклама ещё не загрузилась");
    }
  }

  public static void HideBanner(){
    if (BottomAd != null) {
      BottomAd.Hide ();
    }
  }

  public static void ShowBanner(){
    if (BottomAd != null) {
      BottomAd.Show ();
    }
  }

  public void BannerFailedToLoad (object sender, AdFailedToLoadEventArgs args){
    Debug.LogError ("Banner: Реклама не загрузилась");
    Debug.LogError (args.Message);
  }

  public void BannerLoaded (object sender, EventArgs args){
    Debug.Log ("Banner: Реклама загрузилась");
  }

  public void InterstitialFailedToLoad (object sender, AdFailedToLoadEventArgs args){
    Debug.LogError ("Interstitial: Реклама не загрузилась");
    Debug.LogError (args.Message);
  }

  public void InterstitialLoaded (object sender, EventArgs args){
    Debug.Log ("Interstitial: Реклама загрузилась");
  }

  public void InterstitialClosed (object sender, EventArgs args){
    Debug.Log ("Interstitial: Реклама закрыта кнопкой 'закрыть'");
    IntAds.Destroy ();
    PrepareInterstitial ();
  }

  void OnDestroy() {
    BottomAd.OnAdLoaded -= BannerLoaded;
    BottomAd.OnAdFailedToLoad -= BannerFailedToLoad;

    IntAds.OnAdLoaded -= InterstitialLoaded;
    IntAds.OnAdFailedToLoad -= InterstitialFailedToLoad;
    IntAds.OnAdClosed -= InterstitialClosed;
  }
}

Video advertising
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using GoogleMobileAds;
using GoogleMobileAds.Api;

public class RewardedVideo : MonoBehaviour {

  private const string video_id = "ca-app-pub-3940256099942544/5224354917";
  public static RewardBasedVideoAd videoAD;

  bool isAdLoading = false;
  public bool ad_ready = false;
  public bool failed = false;

  void Start () {
    // Чтобы не дублировать Instance, проверяем, существует ли он
    if (videoAD == null) {
      videoAD = RewardBasedVideoAd.Instance;
    }

    videoAD.OnAdLoaded += HandleOnAdLoaded;
    videoAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
    videoAD.OnAdOpening += HandleOnAdOpening;
    videoAD.OnAdStarted += HandleOnAdStarted;
    videoAD.OnAdClosed += HandleOnAdClosed;
    videoAD.OnAdRewarded += HandleOnAdRewarded;
    videoAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;
  }

  public void LoadVideoAd(){
    Debug.Log ("VideoAD: Отправляем запрос. Грузим рекламу");
    videoAD.LoadAd (new AdRequest.Builder ()
      .AddTestDevice (AdRequest.TestDeviceSimulator)
      .AddTestDevice (SystemInfo.deviceUniqueIdentifier.ToUpper())
      .Build (), video_id);
    
    isAdLoading = true;
  }

  public void Prepare(){
    failed = false;
    Debug.LogWarning ("Кнопка подсказки нажата");
    GoogleADS.HideBanner ();
  }

  public void showAd(){
    // Пробуем показать рекламу
    if(failed){
      Debug.Log ("Не удалось загрузить видеорекламу");
    }

    if (ad_ready) {
      Debug.Log ("VideoAD: Показываем рекламу");
      videoAD.Show ();
    }

    if (isAdLoading & !ad_ready & !failed) {
      Debug.Log ("VideoAD: Реклама всё ещё грузится. К показу не готова. Ждём и проверяем готовность каждые 3 секунды");
      Invoke ("showAd", 3);
    }

    if (!isAdLoading & !ad_ready & !failed) {
      Debug.Log ("VideoAD: Нет текущих запросов. Отправляем новый запрос и ждём загрузку");
      LoadVideoAd();
      Invoke ("showAd", 3);
    }
  }

  public void HandleOnAdLoaded (object sender, EventArgs args){
    Debug.Log ("VideoAD: Реклама загружена, всё готово к показу");
    isAdLoading = false;
    ad_ready = true;
  }

  public void HandleOnAdFailedToLoad (object sender, AdFailedToLoadEventArgs args){
    Debug.LogError ("VideoAD: Ошибка. Реклама не загрузилась");
    isAdLoading = false;
    failed = true;
    Debug.LogError (args.Message);
  }

  public void HandleOnAdOpening (object sender, EventArgs args){
    
  }

  public void HandleOnAdStarted (object sender, EventArgs args){
    
  }

  public void HandleOnAdClosed (object sender, EventArgs args){
    Debug.Log ("VideoAD: Реклама закрыта кнопкой 'закрыть'");
    GoogleADS.ShowBanner();
    ad_ready = false;

    //LoadVideoAd ();
  }

  public void HandleOnAdRewarded (object sender, Reward args){
    Debug.Log ("VideoAD: Реклама успешно показана. Получаем вознаграждение");
    //Debug.Log ("reward gained: " + args.Amount + " " + args.Type);
    ad_ready = false;
  }

  public void HandleOnAdLeavingApplication(object sender, EventArgs args){
    Debug.Log ("VideoAD: По рекламе кликнули, пользователь покидает приложение");
    GoogleADS.ShowBanner();
    ad_ready = false;
  }

  void OnDestroy(){
    videoAD.OnAdLoaded -= HandleOnAdLoaded;
    videoAD.OnAdFailedToLoad -= HandleOnAdFailedToLoad;
    videoAD.OnAdOpening -= HandleOnAdOpening;
    videoAD.OnAdStarted -= HandleOnAdStarted;
    videoAD.OnAdClosed -= HandleOnAdClosed;
    videoAD.OnAdRewarded -= HandleOnAdRewarded;
    videoAD.OnAdLeavingApplication -= HandleOnAdLeavingApplication;
  }
}

Here is the link to the project

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Ivanov, 2019-04-21
@keksmr

The new version of the plugin for Unity - AdMob has bugs due to which it does not work

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question