くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

Unity×AdMob×Androidで広告を表示する

Unityでアプリを作っていると何度も公式ドキュメントを見に行くので、よく使うものの備忘録

AdMobのUnityプラグインをダウンロード&デプロイ

ここ(Release Google Mobile Ads Unity Plugin v3.4.0 · googleads/googleads-mobile-unity · GitHub)から、
GoogleMobileAds.unitypackageをダウンロードして取り込めばOK!

基本的なバーナーリクエス

ドキュメント(Get Started  |  AdMob for Unity  |  Google Developers)から

using UnityEngine;
using GoogleMobileAds.Api;


public class AdMobBanner : MonoBehaviour {
    private string adUnitId = "INSERT_ANDROID_BANNER_AD_UNIT_ID_HERE";
    private BannerView bannerView ;

    void Start () {
        // Create a banner at the top of the screen.
        bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Top);

        // Create an ad request.
        AdRequest request = new AdRequest.Builder()
            .AddTestDevice(AdRequest.TestDeviceSimulator)       // Simulator.
            .Build();
        
        // Add Event Handler
        bannerView.OnAdLoaded             += HandleOnAdLoaded;             // ad request has successfully loaded.
        bannerView.OnAdFailedToLoad       += HandleOnAdFailedToLoad;       // ad request failed to load.
        bannerView.OnAdOpened             += HandleOnAdOpened;             // ad is clicked.
        bannerView.OnAdClosed             += HandleOnAdClosed;             // the user returned from the app after an ad click.
        bannerView.OnAdLeavingApplication += HandleOnAdLeavingApplication; // the ad click caused the user to leave the application.

        // Load
        bannerView.LoadAd(request);
    }

    public void HandleOnAdLoaded(object sender, EventArgs args) {}
    public void HandleOnAdFailedToLoad (object sender, AdFailedToLoadEventArgs args) {}
    public void HandleOnAdOpened(object sender, EventArgs args) {}
    public void HandleOnAdClosed(object sender, EventArgs args) {}
    public void HandleOnAdLeavingApplication(object sender, EventArgs args) {}
}

バーナーサイズ(AdSize)とポジション(AdPosition)は、以下な感じ。

AdSize WxH AdPosition
Banner 320x50 Top
MediumRectangle 300x250 Bottom
IABBanner 468x60 TopLeft
Leaderboard 728x90 TopRight
SmartBanner BottomLeft
BottomRight
Center

基本的なインタースティシャル広告リクエス

基本的にはバーナー広告と同じ感じ。 終了時などに使うので、Application.Quit()を呼んだりすると、Handlerの処理が必要に。

using System;
using UnityEngine;
using GoogleMobileAds.Api;

public class AdMobInterstitial : MonoBehaviour {
    private string adUnitId = "INSERT_ANDROID_INTERSTITIAL_AD_UNIT_ID_HERE";
    private InterstitialAd interstitial ;


    // Use this for initialization
    void Start() {
        // Initialize an InterstitialAd.
        interstitial = new InterstitialAd(adUnitId);

        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder()
            .AddTestDevice(AdRequest.TestDeviceSimulator)       // Simulator.
            .Build();

        // Add Event Handler
        interstitial.OnAdLoaded             += HandleOnAdLoaded;             // ad request has successfully loaded.
        interstitial.OnAdFailedToLoad       += HandleOnAdFailedToLoad;       // ad request failed to load.
        interstitial.OnAdOpened             += HandleOnAdOpened;             // ad is clicked.
        interstitial.OnAdClosed             += HandleOnAdClosed;             // the user returned from the app after an ad click.
        interstitial.OnAdLeavingApplication += HandleOnAdLeavingApplication; // the ad click caused the user to leave the application.

        // Load the interstitial with the request.
        interstitial.LoadAd(request);
    }

    public void Show() {
        if(interstitial.IsLoaded()) {
            interstitial.Show();
        } else {
            Application.Quit();
        }
    }

    public void HandleOnAdLoaded(object sender, EventArgs args) {}
    public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args) {}
    public void HandleOnAdOpened(object sender, EventArgs args) {}
    public void HandleOnAdClosed(object sender, EventArgs args) {
        Application.Quit();
    }
    public void HandleOnAdLeavingApplication(object sender, EventArgs args) {}
}

基本的な動画リワード広告リクエス

ドキュメント(動画リワード広告メディエーション  |  AdMob by Google  |  Firebase)から。
動画見たあとの報酬受取処理(rewardedHandler)とか、一度再生したら再読込が必要などめんどくさい。。

using System;
using UnityEngine;
using GoogleMobileAds.Api;

public class AdMobReward : MonoBehaviour {
    private string adUnitId = "INSERT_AD_UNIT_HERE";
    private AdRequest adRequest;
    private RewardBasedVideoAd rewardBasedVideo;
    private Action rewardedHandler;
    private static bool rewardBasedEventHandlersSet = false;

    // Use this for initialization
    void Start() {
        rewardBasedVideo = RewardBasedVideoAd.Instance;
        
        // Create an empty ad request.
        adRequest = new AdRequest.Builder()
            .AddTestDevice(AdRequest.TestDeviceSimulator)       // Simulator.
            .Build();

        // Reward based video instance is a singleton. Register handlers once to avoid duplicate events.
        if (!rewardBasedEventHandlersSet) {
            rewardBasedVideo.OnAdLoaded             += HandleRewardBasedVideoLoaded;          // ad has been received.
            rewardBasedVideo.OnAdFailedToLoad       += HandleRewardBasedVideoFailedToLoad;    // ad has failed to load.
            rewardBasedVideo.OnAdOpening            += HandleRewardBasedVideoOpened;          // ad is opened.
            rewardBasedVideo.OnAdStarted            += HandleRewardBasedVideoStarted;         // ad has started playing.
            rewardBasedVideo.OnAdRewarded           += HandleRewardBasedVideoRewarded;        // ad has rewarded the user.
            rewardBasedVideo.OnAdClosed             += HandleRewardBasedVideoClosed;          // ad is closed.
            rewardBasedVideo.OnAdLeavingApplication += HandleRewardBasedVideoLeftApplication; // ad is leaving the application.

            rewardBasedEventHandlersSet = true;
        }

        // Load
        rewardBasedVideo.LoadAd(adRequest, adUnitId);
    }


    public void Show(Action handler) {
        if (rewardBasedVideo.IsLoaded()) {
            rewardedHandler = handler;
            rewardBasedVideo.Show();
        }
    }

    public void HandleRewardBasedVideoLoaded(object sender, EventArgs args) {}
    public void HandleRewardBasedVideoFailedToLoad(object sender, EventArgs args) {}
    public void HandleRewardBasedVideoOpened(object sender, EventArgs args) {}
    public void HandleRewardBasedVideoStarted(object sender, EventArgs args) {}

    public void HandleRewardBasedVideoRewarded(object sender, Reward args) {
        //報酬受け取り時の処理
        rewardedHandler();
    }

    public void HandleRewardBasedVideoClosed(object sender, EventArgs args) {
        //動画を閉じたときに、次の動画を読み込む
        if(!rewardBasedVideo.IsLoaded()) {
            rewardBasedVideo.LoadAd(adRequest, adUnitId); // Load
        }
    }

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

参考にしたサイト