Requirements
- Unity 4 or higher
- To deploy on iOS
- Xcode 7.0 or higher
- Google Mobile Ads SDK 7.7.0 or higher
- To deploy on Android
- Android SDK 3.2 or higher
- Google Play services 7.5 or higher
DownloadGoogleMobileAds.unitypackage
Import the plugin into your game
1. Open your project in the Unity editor.
Select Assets > Import Package > Custom Package and find the GoogleMobileAdsPlugin.unitypackage file you downloaded.
2. Make sure all of the files are selected and click Import.
Unity plugin API
You can use the common C# API in the Google Mobile Ads plugin to request the interstitial ads. The code can be written once and deployed to both Android and iOS.
How to request for an interstitial ad?
Let's understand it with code.
using GoogleMobileAds.Api;
...
private void RequestInterstitial()
{
#if UNITY_ANDROID
string adUnitId = "INSERT_ANDROID_INTERSTITIAL_AD_UNIT_ID_HERE";
#elif UNITY_IPHONE
string adUnitId = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE";
#else
string adUnitId = "unexpected_platform";
#endif
// Initialize an InterstitialAd.
InterstitialAd interstitial = new InterstitialAd(adUnitId);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
interstitial.LoadAd(request);
// EventHandlers
// Called when an ad request has successfully loaded.
interstitial.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
interstitial.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is clicked.
interstitial.OnAdOpened += HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
interstitial.OnAdClosed += HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
interstitial.OnAdLeavingApplication += HandleOnAdLeavingApplication;
}
You only need to register for the events you care about.
Here, we will use the only OnAdFailedToLoad, where this handler calls when ads load function fails.
The OnAdFailedToLoad event contains special event arguments. It passes an instance of HandleAdFailedToLoadEventArgs with a Message describing the error:
public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
print("Interstitial Failed to load: " + args.Message);
// Handle the ad failed to load event.
};
Unlike banner ads, we have to call interstitial ads explicitly.
At an appropriate stopping point in your game, such as when the current level ends, check that the interstitial ad is ready before showing it. A good place to show an interstitial is when the game is over:
private void GameOver()
{
if(interstitial.IsLoaded())
{
interstitial.Show();
}
}
Clean up interstitial ads
When you are finished with the Interstitial Ad, make sure to call the Destroy() method before dropping your reference to it:
interstitial.Destroy();