<br />

[Rewarded interstitial](https://support.google.com/admob/answer/9884467) is a type of
incentivized ad format that lets you offer rewards for ads that appear
automatically during natural app transitions. Unlike rewarded ads, users aren't
required to opt-in to view a rewarded interstitial.

## Prerequisites

Before you continue, [set up Google Mobile Ads Unity Plugin](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/quick-start.md.txt).

## Always test with test ads

The following sample code contains an ad unit ID which you can use to request
test ads. It's been specially configured to return test ads rather than
production ads for every request, making it safe to use.

However, after you've registered an app in the
Ad Manager web interface and created your own ad unit
IDs for use in your app, explicitly [configure your device as a test
device](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/test-ads#enable_test_devices) during
development.

`/21775744923/example/interstitial`

## Initialize Google Mobile Ads Unity Plugin

Before loading ads, have your app initialize Google Mobile Ads Unity Plugin by calling
`MobileAds.Initialize()`. This needs to be done only once, ideally at app launch.

```c#
using GoogleMobileAds;
using GoogleMobileAds.Api;

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

If you're using mediation, wait until the callback occurs before loading ads as
this will ensure that all mediation adapters are initialized.

## Implementation

The main steps to integrate rewarded interstitial ads are:

1. Load the rewarded interstitial ad
2. \[Optional\] Validate server-side verification (SSV) callbacks
3. Show the rewarded interstitial ad with reward callback
4. Listen to rewarded interstitial ad events
5. Clean up the rewarded interstitial ad
6. Preload the next rewarded interstitial ad

### Load the rewarded interstitial ad

Loading a rewarded interstitial ad is accomplished using the static `Load()`
method on the `RewardedInterstitialAd` class. The load method requires an ad
unit ID, an `AdManagerAdRequest` object, and a completion
handler which gets called when ad loading succeeds or fails. The loaded
`RewardedInterstitialAd` object is provided as a parameter in the completion
handler. The example below shows how to load a `RewardedInterstitialAd`.

```c#

  // This ad unit is configured to always serve test ads.
  private string _adUnitId = "/21775744923/example/rewarded-interstitial";

  private RewardedInterstitialAd _rewardedInterstitialAd;

  /// <summary>
  /// Loads the rewarded interstitial ad.
  /// </summary>
  public void LoadRewardedInterstitialAd()
  {
      // Clean up the old ad before loading a new one.
      if (_rewardedInterstitialAd != null)
      {
            _rewardedInterstitialAd.Destroy();
            _rewardedInterstitialAd = null;
      }

      Debug.Log("Loading the rewarded interstitial ad.");

      // create our request used to load the ad.
      var adRequest = new AdManagerAdRequest();
      adRequest.Keywords.Add("unity-admob-sample");

      // send the request to load the ad.
      RewardedInterstitialAd.Load(_adUnitId, adRequest,
          (RewardedInterstitialAd ad, LoadAdError error) =>
          {
              // if error is not null, the load request failed.
              if (error != null || ad == null)
              {
                  Debug.LogError("rewarded interstitial ad failed to load an ad " +
                                 "with error : " + error);
                  return;
              }

              Debug.Log("Rewarded interstitial ad loaded with response : "
                        + ad.GetResponseInfo());

              _rewardedInterstitialAd = ad;
          });
  }
```

> [!WARNING]
> **Warning:** Attempting to load a new ad from the ad request completion block when an ad failed to load is strongly discouraged. If you must load an ad from the ad request completion block, limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.


> [!TIP]
> **Tip:** You can use ad load calls to build up a cache of preloaded ads before you intend to show them, so that ads can be shown with zero latency when needed. Because ads expire after an hour, you should clear this cache and reload with new ads every hour.

<br />

### \[Optional\] Validate server-side verification (SSV) callbacks

Apps that require extra data in [server-side verification](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/ssv.md.txt)
callbacks should use the custom data feature of rewarded interstitial ads.
Any string value set on a rewarded ad object is passed to the `custom_data`
query parameter of the SSV callback. If no custom data value is set, the
`custom_data` query parameter value won't be included in the SSV callback.

The following code sample demonstrates how to set the SSV options after the
rewarded interstitial ad is loaded.

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

        // If the operation completed successfully, no error is returned.
        Debug.Log("Rewarded interstitial 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);
});
```

If you want to set the custom reward string, you must do so before showing the
ad.

> [!IMPORTANT]
> **Key Point:** The custom reward string is [percent escaped](https://en.wikipedia.org/wiki/Percent-encoding) and might require decoding when parsed from the SSV callback.

### Show the rewarded interstitial ad with reward callback

When presenting your ad, you must provide a callback to handle the reward for
the user. Ads can only be shown once per load. Use the `CanShowAd()` method to
verify that the ad is ready to be shown.

The following code presents the best method for displaying a rewarded
interstitial ad.

```c#
public void ShowRewardedInterstitialAd()
{
    const string rewardMsg =
        "Rewarded interstitial ad rewarded the user. Type: {0}, amount: {1}.";

    if (rewardedInterstitialAd != null && rewardedInterstitialAd.CanShowAd())
    {
        rewardedInterstitialAd.Show((Reward reward) =>
        {
            // TODO: Reward the user.
            Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
        });
    }
}
```

> [!IMPORTANT]
> **Key Point:** Before displaying a rewarded interstitial ad to users, you must present the user with an intro screen that provides clear reward messaging and an option to skip the ad before it starts. [Learn more](https://support.google.com/admob/answer/9884467).

### Listen to rewarded interstitial ad events

To further customize the behavior of your ad, you can hook into a number of
events in the ad's lifecycle. Listen for these events by registering a delegate
as shown below.

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

### Clean up the rewarded interstitial ad

When you are finished with a `RewardedInterstitialAd`, make sure to call the
`Destroy()` method before dropping your reference to it:

```c#
_rewardedInterstitialAd.Destroy();
```

This notifies the plugin that the object is no longer used and the memory it
occupies can be reclaimed. Failure to call this method results in memory leaks.

### Preload the next rewarded interstitial ad

`RewardedInterstitialAd` is a one-time-use object. This means once a rewarded
interstitial ad is shown, the object can't be used again. To request another
rewarded interstitial ad, you'll need to load a new `RewardedInterstitialAd`
object.

To prepare an rewarded interstitial ad for the next impression opportunity,
preload the rewarded interstitial ad once the `OnAdFullScreenContentClosed` or
`OnAdFullScreenContentFailed` ad event is raised.

```c#
private void RegisterReloadHandler(RewardedInterstitialAd ad)
{
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += ()
    {
        Debug.Log("Rewarded interstitial ad full screen content closed.");

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

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

## Additional resources

- [HelloWorld example](https://github.com/googleads/googleads-mobile-unity/tree/main/samples/HelloWorld): A minimal implementation of all ad formats.