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
Download GoogleMobileAds.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 banner ads. The code can be written once and deployed to both Android and iOS.
How to request for banner ad?
Let's understand it with code.
using GoogleMobileAds.Api;
...
private void RequestBanner()
{
#if UNITY_EDITOR
string adUnitId = "unused";
#elif UNITY_ANDROID
string adUnitId = "INSERT_ANDROID_BANNER_AD_UNIT_ID_HERE";
#elif UNITY_IPHONE
string adUnitId = "INSERT_IOS_BANNER_AD_UNIT_ID_HERE";
#else
string adUnitId = "unexpected_platform";
#endif
// Create a 320x50 banner at the top of the screen.
BannerView bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
// The AdPosition enum specifies where to place the banner.
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the banner with the request.
bannerView.LoadAd(request);
// EventHandlers
// Called when an ad request has successfully loaded.
bannerView.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
bannerView.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is clicked.
bannerView.OnAdOpened += HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
bannerView.OnAdClosed += HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
bannerView.OnAdLeavingApplication += HandleOnAdLeavingApplication;
}
You only need to register for the events you care about.
Here, we will use only HandleOnAdLoaded, where this handler calls when ad loaded successfully.
public void HandleOnAdLoaded(object sender, EventArgs args)
{
print("OnAdLoaded event received.");
// Handle the ad loaded event.
}
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.
};
Hide and show banners
By default, banners are visible. To temporarily hide a banner, call the following:
bannerView.Hide();
To show it again, call the following:
bannerView.Show();
Clean up banner ads
When you are finished with a BannerView, make sure to call the Destroy() method before dropping your reference to it:
bannerView.Destroy();