リワード広告

リワード広告は、ユーザーが広告を操作することと引き換えにアプリ内で報酬を獲得できる広告です。このガイドでは、AdMob のリワード広告を Unity アプリに組み込む方法について説明します。

ケーススタディ 1ケーススタディ 2 でお客様の成功事例をご覧いただけます。

このガイドでは、Unity アプリにリワード広告を組み込む方法について説明します。

前提条件

テストは必ずテスト広告で行う

以下のサンプルコードには、テスト広告のリクエストに使用できる広告ユニット ID が含まれています。この ID は、どのリクエストに対しても実際の広告ではなくテスト広告を返すように設定されており、安全に使用できます。

ただし、AdMob ウェブ インターフェースにアプリを登録し、アプリで使用する独自の広告ユニット ID を作成した後は、開発中に明示的にデバイスをテストデバイスとして設定する必要があります。

Android

ca-app-pub-3940256099942544/5224354917

iOS

ca-app-pub-3940256099942544/1712485313

Mobile Ads SDK を初期化する

広告を読み込む前に MobileAds.Initialize() を呼び出して、アプリで Mobile Ads SDK を初期化します。この処理は 1 回だけ行います(アプリの起動時に行うのが理想的です)。

using GoogleMobileAds;
using GoogleMobileAds.Api;

public class GoogleMobileAdsDemoScript : MonoBehaviour
{
    public void Start()
    {
        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            // This callback is called once the MobileAds SDK is initialized.
        });
    }
}

メディエーションを使用している場合は、すべてのメディエーション アダプタを確実に初期化できるよう、広告を読み込む前にコールバックが発生してください。

実装

リワード広告を組み込む主な手順は、以下のとおりです。

  1. リワード広告を読み込む
  2. [省略可] サーバーサイド認証(SSV)コールバックを検証する
  3. リワード広告を報酬のコールバック付きで表示する
  4. リワード広告のイベントをリッスンする
  5. リワード広告をクリーンアップする
  6. 次のリワード広告をプリロードする

リワード広告を読み込む

リワード広告の読み込みは、RewardedAd クラスで静的 Load() メソッドを使用して行います。読み込まれた RewardedAd オブジェクトは、完了ハンドラのパラメータとして提供されます。以下の例は、RewardedAd を読み込む方法を示しています。


  // These ad units are configured to always serve test ads.
#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;

  /// <summary>
  /// Loads the rewarded ad.
  /// </summary>
  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;
          });
  }

[省略可] サーバーサイド認証(SSV)コールバックを検証する

サーバーサイド認証コールバックで追加データを必要とするアプリでは、リワード広告のカスタムデータ機能を使用する必要があります。リワード広告オブジェクトに設定されている文字列値はすべて、SSV コールバックの custom_data クエリ パラメータに渡されます。カスタムデータ値が設定されていない場合、SSV コールバックは custom_data クエリ パラメータ値を持ちません。

次のコード例は、リワード広告の読み込み後に SSV のオプションを設定する方法を示しています。

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

    // If the operation completed successfully, no error is returned.
    Debug.Log("Rewarded ad loaded with response : " + ad.GetResponseInfo());

    // Create and pass the SSV options to the rewarded ad.
    var options = new ServerSideVerificationOptions
                          .Builder()
                          .SetCustomData("SAMPLE_CUSTOM_DATA_STRING")
                          .Build()
    ad.SetServerSideVerificationOptions(options);

});

カスタム リワード文字列を設定する場合は、広告を表示する前に行う必要があります。

リワード広告を報酬のコールバック付きで表示する

広告を表示する際には、ユーザーへの報酬を処理するコールバックを指定する必要があります。読み込んだ広告は 1 回だけ表示できます。広告を表示する準備ができていることを確認するには、CanShowAd() メソッドを使用します。

以下のコードは、リワード広告を表示するための最適な方法を示しています。

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));
        });
    }
}

リワード広告のイベントをリッスンする

広告の動作をより細かくカスタマイズするには、広告のライフサイクルで生じるさまざまなイベント(開始、終了など)を利用します。これらのイベントをリッスンするには、以下のようにデリゲートを登録します。

private void RegisterEventHandlers(RewardedAd ad)
{
    // Raised when the ad is estimated to have earned money.
    ad.OnAdPaid += (AdValue adValue) =>
    {
        Debug.Log(String.Format("Rewarded ad paid {0} {1}.",
            adValue.Value,
            adValue.CurrencyCode));
    };
    // Raised when an impression is recorded for an ad.
    ad.OnAdImpressionRecorded += () =>
    {
        Debug.Log("Rewarded ad recorded an impression.");
    };
    // Raised when a click is recorded for an ad.
    ad.OnAdClicked += () =>
    {
        Debug.Log("Rewarded ad was clicked.");
    };
    // Raised when an ad opened full screen content.
    ad.OnAdFullScreenContentOpened += () =>
    {
        Debug.Log("Rewarded ad full screen content opened.");
    };
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Rewarded ad full screen content closed.");
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded ad failed to open full screen content " +
                       "with error : " + error);
    };
}

リワード広告をクリーンアップする

使い終わった RewardedAd への参照を破棄する前に、必ず Destroy() メソッドを呼び出してください。

_rewardedAd.Destroy();

これにより、そのオブジェクトはもう使用されておらず、オブジェクトが占有していたメモリを回収しても問題ないことを、プラグインに通知できます。このメソッドを呼び出さないとメモリリークが発生します。

次のリワード広告をプリロードする

RewardedAd は使い捨てオブジェクトです。一度リワード広告を表示した後、同じオブジェクトを再度使うことはできません。次にリワード広告をリクエストするには、新しい RewardedAd オブジェクトを作成する必要があります。

次のインプレッションの機会に備えてリワード広告を用意するには、広告イベント OnAdFullScreenContentClosed または OnAdFullScreenContentFailed が発生した時点でリワード広告をプリロードするようにします。

private void RegisterReloadHandler(RewardedAd ad)
{
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Rewarded Ad full screen content closed.");

        // Reload the ad so that we can show another as soon as possible.
        LoadRewardedAd();
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded ad failed to open full screen content " +
                       "with error : " + error);

        // Reload the ad so that we can show another as soon as possible.
        LoadRewardedAd();
    };
}

参考情報