Rewarded ads are ads that users have the option of interacting with in exchange for in-app rewards. This guide shows you how to integrate rewarded ads from AdMob into a Unity app.
Read some customer success stories: case study 1, case study 2.This guide explains how to integrate rewarded ads into a Unity app.
Prerequisites
- Complete the Get started guide.
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 AdMob web interface and created your own ad unit IDs for use in your app, explicitly configure your device as a test device during development.
Android
ca-app-pub-3940256099942544/5224354917
iOS
ca-app-pub-3940256099942544/1712485313
Initialize the Mobile Ads SDK
Before loading ads, have your app initialize the Mobile Ads SDK by calling
MobileAds.Initialize()
. This needs to be done only once, ideally at app launch.
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.
});
}
}
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 ads are:
- Load the rewarded ad
- [Optional] Validate server-side verification (SSV) callbacks
- Show the rewarded ad with reward callback
- Listen to rewarded ad events
- Clean up the rewarded ad
- Preload the next rewarded ad
Load the rewarded ad
Loading a rewarded ad is accomplished using the static Load()
method on the
RewardedAd
class. The loaded RewardedAd
object is provided as a
parameter in the completion handler. The example below shows how to load a
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;
});
}
[Optional] Validate server-side verification (SSV) callbacks
Apps that require extra data in server-side verification
callbacks should use the custom data feature of rewarded 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 present in the SSV callback.
The following code sample demonstrates how to set the SSV options after the rewarded ad is loaded.
// 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);
});
If you want to set the custom reward string, you must do so before showing the ad.
Show the rewarded 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 ad.
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));
});
}
}
Listen to rewarded ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: opening, closing, and so on. Listen for these events by registering a delegate as shown below.
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);
};
}
Clean up the rewarded ad
When you are finished with a RewardedAd
, make sure to call the Destroy()
method before dropping your reference to it:
_rewardedAd.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 ad
RewardedAd
is a one-time-use object. This means once a rewarded ad is shown,
the object can't be used again. To request another rewarded ad,
you'll need to create a new RewardedAd
object.
To prepare a rewarded ad for the next impression opportunity, preload the
rewarded ad once the OnAdFullScreenContentClosed
or
OnAdFullScreenContentFailed
ad event is raised.
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();
};
}
Additional resources
- HelloWorld example: A minimal implementation of all ad formats.