Banner ads are rectangular image or text ads that occupy a spot on screen. They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. If you're new to mobile advertising, they're a great place to start. Case study.
This guide shows you how to integrate banner ads from AdMob into a Unity app. In addition to code snippets and instructions, it also includes information about sizing banners properly and links to additional resources.
Prerequisites
- Complete the Get started guide.
Create a BannerView
The first step toward displaying a banner is to create a BannerView
object in
a C# script attached to a GameObject
.
using System;
using UnityEngine;
using GoogleMobileAds.Api;
...
public class GoogleMobileAdsDemoScript : MonoBehaviour
{
private BannerView bannerView;
...
public void Start()
{
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(initStatus => { });
this.RequestBanner();
}
private void RequestBanner()
{
#if UNITY_ANDROID
string adUnitId = "ca-app-pub-3940256099942544/6300978111";
#elif UNITY_IPHONE
string adUnitId = "ca-app-pub-3940256099942544/2934735716";
#else
string adUnitId = "unexpected_platform";
#endif
// Create a 320x50 banner at the top of the screen.
this.bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
}
}
The constructor for a BannerView
has the following parameters:
adUnitId
- The AdMob ad unit ID from which theBannerView
should load ads.AdSize
- The AdMob ad size you'd like to use (consult Banner sizes for details).AdPosition
- The position where the banner ad should be placed. TheAdPosition
enum lists the valid ad position values.
It is important to note how different ad units are used, depending on the platform. You'll need to use an iOS ad unit for making ad requests on iOS and an Android ad unit for making requests on Android.
(Optional) Custom ad position
For greater control over where a BannerView
is placed on screen than what's
offered by AdPosition
values, use the BannerView
constructor that has x- and
y-coordinates as parameters:
// Create a 320x50 banner ad at coordinate (0,50) on screen.
BannerView bannerView = new BannerView(adUnitId, AdSize.Banner, 0, 50);
The top-left corner of the BannerView
will be positioned at the x and y values
passed to the constructor, where the origin is the top-left of the screen.
(Optional) Custom ad sizes
In addition to using an AdSize constant, you can also specify a custom size for your ad:
AdSize adSize = new AdSize(250, 250);
BannerView bannerView = new BannerView(adUnitId, adSize, AdPosition.Bottom);
Always test with test ads
The sample code above contains an ad unit ID and you're free to request ads with it. It's been specially configured to return test ads rather than production ads for every request, which makes it safe to use.
However, once you register an app in the AdMob UI and create your own ad unit IDs for use in your app, you'll need to explicitly configure your device as a test device when you're developing. This is extremely important. Testing with real ads (even if you never tap on them) is against AdMob policy and can cause your account to be suspended. Read Test Ads for information on how you can make sure you always get test ads when developing.
Load an ad
Once the BannerView
is instantiated, the next step is to load an ad. That's
done with the loadAd()
method in the BannerView
class. It takes an
AdRequest
argument, which holds runtime information (such as targeting info)
about a single ad request.
Here's an example that shows how to load an ad:
... private void RequestBanner() { #if UNITY_ANDROID string adUnitId = "ca-app-pub-3940256099942544/6300978111"; #elif UNITY_IPHONE string adUnitId = "ca-app-pub-3940256099942544/2934735716"; #else string adUnitId = "unexpected_platform"; #endif // Create a 320x50 banner at the top of the screen. this.bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top); // Create an empty ad request. AdRequest request = new AdRequest.Builder().Build(); // Load the banner with the request. this.bannerView.LoadAd(request); } ...
That's it! Your app is now ready to display banner ads from AdMob.
Ad events
To further customize the behavior of your ad, you can hook into a number of
events in the ad's lifecycle: loading, opening, closing, and so on. Listen for
these events by registering a delegate for the appropriate EventHandler
, as
shown below.
... using System; using UnityEngine; using GoogleMobileAds.Api; ... public class GoogleMobileAdsDemoScript : MonoBehaviour { private BannerView bannerView; public void Start() { this.RequestBanner(); } private void RequestBanner() { #if UNITY_ANDROID string adUnitId = "ca-app-pub-3940256099942544/6300978111"; #elif UNITY_IPHONE string adUnitId = "ca-app-pub-3940256099942544/2934735716"; #else string adUnitId = "unexpected_platform"; #endif this.bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top); // Called when an ad request has successfully loaded. this.bannerView.OnAdLoaded += this.HandleOnAdLoaded; // Called when an ad request failed to load. this.bannerView.OnAdFailedToLoad += this.HandleOnAdFailedToLoad; // Called when an ad is clicked. this.bannerView.OnAdOpening += this.HandleOnAdOpened; // Called when the user returned from the app after an ad click. this.bannerView.OnAdClosed += this.HandleOnAdClosed; // Create an empty ad request. AdRequest request = new AdRequest.Builder().Build(); // Load the banner with the request. this.bannerView.LoadAd(request); } public void HandleOnAdLoaded(object sender, EventArgs args) { MonoBehaviour.print("HandleAdLoaded event received"); } public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args) { MonoBehaviour.print("HandleFailedToReceiveAd event received with message: " + args.LoadAdError.GetMessage()); } public void HandleOnAdOpened(object sender, EventArgs args) { MonoBehaviour.print("HandleAdOpened event received"); } public void HandleOnAdClosed(object sender, EventArgs args) { MonoBehaviour.print("HandleAdClosed event received"); } }
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)
{
MonoBehaviour.print("Banner failed to load: " + args.Message);
// Handle the ad failed to load event.
};
Ad event | Description |
---|---|
OnAdLoaded |
The OnAdLoaded event is executed when an ad has finished
loading. |
OnAdFailedToLoad |
The OnAdFailedToLoad event is invoked when an ad fails to
load. The Message parameter describes the type of failure that
occurred. |
OnAdOpening |
This method is invoked when the user taps on an ad. If you're using an analytics package to track clickthroughs, this is a good place to record one. |
OnAdClosed |
When a user returns to the app after viewing an ad's destination URL, this method is invoked. Your app can use it to resume suspended activities or perform any other work necessary to make itself ready for interaction. |
Banner sizes
The table below lists the standard banner sizes.
Size in dp (WxH) | Description | Availability | AdSize constant |
---|---|---|---|
320x50 | Standard Banner | Phones and Tablets | BANNER |
320x100 | Large Banner | Phones and Tablets | LARGE_BANNER |
300x250 | IAB Medium Rectangle | Phones and Tablets | MEDIUM_RECTANGLE |
468x60 | IAB Full-Size Banner | Tablets | FULL_BANNER |
728x90 | IAB Leaderboard | Tablets | LEADERBOARD |
Provided width x Adaptive height | Adaptive banner | Phones and Tablets | N/A |
Screen width x 32|50|90 | Smart banner | Phones and Tablets | SMART_BANNER |
Learn more about Adaptive Banners, intended to replace Smart Banners. |
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();
This notifies the plugin that the object is no longer used and the memory it occupied can be reclaimed. Failure to call this method results in memory leaks.