リワード広告は、ユーザーが広告を操作することと引き換えにアプリ内で報酬を獲得できる広告です。このガイドでは、AdMob のリワード広告を Unity アプリに統合する方法を説明します。
お客様成功事例については、事例紹介 1、事例紹介 2 をご覧ください。
このガイドでは、リワード広告を Unity アプリに統合する方法について説明します。
Prerequisites
- スタートガイドの手順を完了していること
常にテスト広告でテストする
以下のサンプルコードには、テスト広告をリクエストする際に使用できる広告ユニット 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.
});
}
}
メディエーションを使用している場合は、すべてのメディエーション アダプタが確実に初期化されるため、広告が読み込まれるまでコールバックが発生するのを待ちます。
実装
リワード広告を組み込む主な手順は、以下のとおりです。
- リワード広告を読み込む
- [省略可] サーバーサイド認証(SSV)コールバックを検証する
- リワード コールバックでリワード広告を表示する
- リワード広告イベントをリッスンする
- リワード広告をクリーンアップする
- 次のリワード広告をプリロードする
リワード広告を読み込む
リワード広告の読み込みは、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();
adRequest.Keywords.Add("unity-admob-sample");
// 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();
};
}
参考情報
サンプル
- HelloWorld の例: すべての広告フォーマットの最小限の実装。