Banner Ads

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.

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 Get Started. Your Unity app should already have the Google Mobile Ads Unity plugin imported.

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 GoogleMobileAds.Api;
...
public class GoogleMobileAdsDemoScript : MonoBehaviour
{
    private BannerView bannerView;
    …
    public void Start()
    {
        #if UNITY_ANDROID
            string appId = "ca-app-pub-3940256099942544~3347511713";
        #elif UNITY_IPHONE
            string appId = "ca-app-pub-3940256099942544~1458002511";
        #else
            string appId = "unexpected_platform";
        #endif

        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize(appId);

        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.
        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 the BannerView should load ads.
  • AdSize - The AdMob ad size you'd like to use (see Banner sizes for details).
  • AdPosition - The position where the banner ad should be placed. The AdPosition 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 BannerViewconstructor 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. See 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:

...
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

        // Create a 320x50 banner at the top of the screen.
        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.
        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 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

        bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);

        // 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.OnAdOpening += 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;

        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder().Build();

        // Load the banner with the request.
        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.Message);
    }

    public void HandleOnAdOpened(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdOpened event received");
    }

    public void HandleOnAdClosed(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdClosed event received");
    }

    public void HandleOnAdLeavingApplication(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdLeavingApplication 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 eventDescription
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.
OnAdLeavingApplication This method is invoked after onAdOpened, when a user click opens another app (such as the Google Play store), backgrounding the current app.

The following banner sizes are supported:

Size (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
Screen width x 32|50|90 Smart Banner Phones and Tablets SMART_BANNER

Smart Banners

Smart Banners are ad units that render screen-width banner ads on any screen size across different devices in either orientation. Smart Banners help deal with increasing screen fragmentation across different devices by "smartly" detecting the width of the device in its current orientation and making the ad view that size.

Three ad heights are implemented in smart banners:

Ad height Screen height
32dp ≤ 400dp
50dp > 400dp and ≤ 720dp
90dp > 720dp

Typically, Smart Banners on phones have a height of 50dp in portrait and 32dp in landscape. On tablets, height is normally 90dp in both orientations.

When an image ad isn't large enough to take up the entire allotted space, the image will be centered, and the space on either side will be filled in.

To use Smart Banners, specify the AdSize.SmartBanner for the ad size when creating a BannerView. For example:

// Create a Smart Banner at the top of the screen.
BannerView bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Top);

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.

Additional resources

Samples

Next steps

Send feedback about...

Google AdMob > Mobile Ads SDK > Unity
Google AdMob > Mobile Ads SDK > Unity
Need help? Visit our support page.