Interstitial Ad
Note
Make sure you've done SDK Initialization before attempting to load any ads.
Use InterstitialAd to load and display an interstitial.
Tip
You can find a functional code in "Interstitial" sample.
Declare variable
InterstitialAd implements IDisposable.
Dispose() severs the event chain (your callbacks will no longer be called) and lets the engine free the resources (e.g. held by underlying AndroidJavaObject).
Calling Dispose() before losing the reference might have performance benefits.
Thus we shall keep a reference in some relatively persistent variable.
For example, an i-var on MonoBehaviour.
using System;
using System.Collections;
using AppstockSDK.Api;
using UnityEngine;
#nullable enable
namespace AppstockSDK.Demo.Interstitial
{
public class InterstitialDemo : MonoBehaviour
{
[SerializeField] private bool showVideoAd;
private IInterstitialAd? _adUnit;
The other property -- showVideoAd
lets us customize the content of the interstitial in editor (on scene).
Instantiation
Call the constructor and set other parameters.
_adUnit = showVideoAd
? new InterstitialAd()
{
PlacementID = "7",
AdUnitFormats = new []{ AdFormat.Video },
}
: new InterstitialAd()
{
PlacementID = "5",
};
Loading the Ad
Once all properties are set, call LoadAd().
_adUnit.LoadAd();
Listening to events
InterstitialAd exposes few events.
OnAdLoaded is useful to know you can call Show(Action?).
OnAdFailed and OnAdClosed are useful to dispose of the no-longer-useful ad unit.
In the sample the script subscribes to all events and logs whenever they are fired.
SubscribeToEvents(_adUnit);
_adUnit.LoadAd();
private void SubscribeToEvents(IInterstitialAd adUnit)
{
adUnit.OnAdLoaded += OnAdUnitLoaded;
adUnit.OnAdDisplayed += OnAdUnitDisplayed;
adUnit.OnAdFailed += OnAdUnitFailed;
adUnit.OnAdClicked += OnAdUnitClicked;
adUnit.OnAdClosed += OnAdUnitClosed;
}
private void OnAdUnitLoaded()
{
Debug.Log($"[{DateTime.Now:O}] Ad Loaded.");
_adUnit?.Show();
}
private void OnAdUnitFailed(AdError? adError)
{
Debug.LogError($"[{DateTime.Now:O}] Ad Failed: {adError?.Message}.");
DropAdUnit();
}
private void OnAdUnitDisplayed() => Debug.Log($"[{DateTime.Now:O}] Ad Displayed.");
private void OnAdUnitClicked() => Debug.Log($"[{DateTime.Now:O}] Ad Clicked.");
private void OnAdUnitClosed()
{
Debug.Log($"[{DateTime.Now:O}] Ad Closed.");
DropAdUnit();
}
Destroying the ad unit
Unsubscribe from events, call Dispose() and clear the reference i-var.
private void UnsubscribeFromEvents(IInterstitialAd adUnit)
{
adUnit.OnAdLoaded -= OnAdUnitLoaded;
adUnit.OnAdDisplayed -= OnAdUnitDisplayed;
adUnit.OnAdFailed -= OnAdUnitFailed;
adUnit.OnAdClicked -= OnAdUnitClicked;
adUnit.OnAdClosed -= OnAdUnitClosed;
}
private void DropAdUnit()
{
if (_adUnit is null)
{
return;
}
UnsubscribeFromEvents(_adUnit);
_adUnit.Dispose();
_adUnit = null;
}