UnityアプリでAdMobインタースティシャル広告が2回目以降表示されない
連続でインタースティシャル広告が表示されないという状況になってどのように対応をしたのかメモを残します。
結論は以下のコードでできました。
public InterstitialAd _interstitial;
void Start()
{
RequestInterstitial();
// インタースティシャル広告が閉じられた際のコールバックを設定
InterstitialAd.Load(adUnitId, adRequest,
(InterstitialAd ad, LoadAdError error) =>
{
ad.OnAdFullScreenContentClosed += () =>
{
DestroyInterstitial();
RequestInterstitial();
};
}
}
/// <summary>
/// インタースティシャル読み込み
/// </summary>
public void RequestInterstitial()
{
---省略----
InterstitialAd.Load(adUnitId, adRequest,
(InterstitialAd ad, LoadAdError error) =>
{
ad.OnAdFullScreenContentClosed += () =>
{
DestroyInterstitial();
InitInterstitial();
Debug.Log("Interstitial ad full screen content closed.");
};
});
}
/// <summary>
/// インタースティシャル削除
/// </summary>
public void DisplayInterstitial()
{
if (_interstitial != null )
{
_interstitial.Destroy();
}
}
上記のコードの機能と流れは
`InterstitialAd _interstitial;`: インタースティシャル広告を管理するための `InterstitialAd` クラスのインスタンスを宣言しています。
`Start()` メソッド: アプリケーションの開始時に実行されるメソッドです。
`RequestInterstitial()` メソッドを呼び出して、初期のインタースティシャル広告を要求します。
`OnAdFullScreenContentClosed` イベントハンドラを設定しています。このイベントは、ユーザーがインタースティシャル広告を閉じたときに呼び出されます。
イベントが発生した際には、`DestroyInterstitial()` メソッドで現在の広告を破棄し、新しい広告を要求する `RequestInterstitial()` メソッドを呼び出します。
`RequestInterstitial()` メソッド: インタースティシャル広告を読み込むためのメソッドです。
AdMobの広告ユニットIDを設定し、新しい `InterstitialAd` インスタンスを作成します。
`AdRequest` クラスを使用して広告のリクエストを構築し、それを使用して `_interstitial` インスタンスに広告を読み込みます。
`DisplayInterstitial()` メソッド: インタースティシャル広告を表示するためのメソッドです。
`_interstitial` インスタンスが存在し、nullでない場合に、`Destroy()` メソッドを呼び出して現在の広告を削除します。これにより、新しい広告を要求する準備が整います。
上記の対応を入れるとユーザーが広告を閉じると、新しい広告が要求され、アプリ内で連続してインタースティシャル広告が表示されるようになっています。