<br />

Banner views 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 views 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

Before you continue, [set up Google Mobile Ads Unity Plugin](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/quick-start.md.txt).

## 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
Ad Manager web interface and created your own ad unit
IDs for use in your app, explicitly [configure your device as a test
device](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/test-ads#enable_test_devices) during
development.

`/21775744923/example/interstitial`

## Initialize Google Mobile Ads Unity Plugin

Before loading ads, have your app initialize Google Mobile Ads Unity Plugin by calling
`MobileAds.Initialize()`. This needs to be done only once, ideally at app launch.

```c#
using GoogleMobileAds;
using GoogleMobileAds.Api;

public class GoogleMobileAdsDemoScript : MonoBehaviour
{
    public void Start()
    {
        // Initialize Google Mobile Ads Unity Plugin.
        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.

## BannerView example

The following sample code details how to use the banner view. In the example,
create an instance of a banner view, use an
`AdManagerAdRequest` to load an ad into the banner view, and
then extend its capabilities by handling lifecycle events.

### Create a banner view

The first step in using a banner view is to create an instance of a banner view.

```c#
// Create a 320x50 banner at top of the screen.
adManagerBannerView = new AdManagerBannerView("AD_UNIT_ID", AdSize.Banner, AdPosition.Top);
```

Replace <var class="readonly" translate="no">AD_UNIT_ID</var> with your ad unit ID.

The constructor for a `AdManagerBannerView` has the following
parameters:

- `adUnitId`: The ad unit ID of the banner ad to load.
- `AdSize`: The [banner size](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/banner.md.txt#banner_sizes) you'd like to use.
- `AdPosition`: The position where the banner views should be placed.

> [!NOTE]
> **Note:** ad unit IDs are platform dependent. Use an iOS ad unit for making ad requests on iOS and an Android ad unit ID for making requests on Android.

#### (Optional) Create a banner view with a custom position

For greater control over where a banner view is placed on screen than what's
offered by `AdPosition` values, use the constructor
that has x- and y-coordinates as parameters:

```c#
// Create a 320x50 banner views at coordinate (0,50) on screen.
adManagerBannerView = new AdManagerBannerView("AD_UNIT_ID", AdSize.Banner, 0, 50);
```

The top-left corner of the banner view is positioned at the x and y values
passed to the constructor, where the origin is the top-left of the screen.

#### (Optional) Create a banner view with a custom size

In addition to using an `AdSize` constant, you can also specify a custom size
for your ad:

```c#
// Create a 250x250 banner at the bottom of the screen.
AdSize adSize = new AdSize(250, 250);
adManagerBannerView = new AdManagerBannerView("AD_UNIT_ID", adSize, AdPosition.Bottom);
```

#### (Optional) Multiple ad sizes

Ad Manager lets you specify multiple ad sizes which could be eligible to serve
in an `AdManagerBannerView`. Before implementing this feature in the SDK, create
a line item targeting the same ad units associated with different size creatives.

In your app, pass multiple `AdSize` parameters into `ValidAdSizes`:

```c#
// Create a 250x250 banner at the bottom of the screen.
adManagerBannerView = new AdManagerBannerView("AD_UNIT_ID", AdSize.Banner, AdPosition.Top);

// Add multiple ad sizes.
adManagerBannerView.ValidAdSizes = new List<AdSize>
{
    AdSize.Banner,
    new AdSize(120, 20),
    new AdSize(250, 250),
};
```

If `AdManagerAdView` changes size at refresh time, your layout should be able to
automatically adapt to the new size. `AdManagerAdView` defaults to the size
passed in the first parameter until the next ad returns.

### Load a banner ad

After the `AdManagerBannerView` is in place, proceed to load
an ad with the `LoadAd()` method in the `AdManagerBannerView`
class. It takes an parameter which holds
runtime information, such as targeting info, exclusion labels, and the publisher
provided ID.

To load an ad, create an `AdManagerAdRequest` and pass it to
the `LoadAd()` method.

```c#
// Send a request to load an ad into the banner view.
adManagerBannerView.LoadAd(new AdManagerAdRequest());
```


> [!TIP]
> **Tip:** You can use ad load calls to build up a cache of preloaded ads before you intend to show them, so that ads can be shown with zero latency when needed. Because ads expire after an hour, you should clear this cache and reload with new ads every hour.

<br />

### Listen to banner view events

To customize the behavior of your ad, you can hook into a number of events in
the ad's lifecycle, such as loading, opening, or closing. To listen for these
events, register a delegate:

```c#
adManagerBannerView.OnBannerAdLoaded += () =>
{
    // Raised when an ad is loaded into the banner view.
};
adManagerBannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
{
    // Raised when an ad fails to load into the banner view.
};
adManagerBannerView.OnAdPaid += (AdValue adValue) =>
{
    // Raised when the ad is estimated to have earned money.
};
adManagerBannerView.OnAdImpressionRecorded += () =>
{
    // Raised when an impression is recorded for an ad.
};
adManagerBannerView.OnAdClicked += () =>
{
    // Raised when a click is recorded for an ad.
};
adManagerBannerView.OnAdFullScreenContentOpened += () =>
{
    // Raised when an ad opened full screen content.
};
adManagerBannerView.OnAdFullScreenContentClosed += () =>
{
    // Raised when the ad closed full screen content.
};
```

### Destroy the banner view

To destroy the banner, call the `Destroy()` method to release resources:

```c#
if (adManagerBannerView != null)
{
    // Always destroy the banner view when no longer needed.
    adManagerBannerView.Destroy();
    adManagerBannerView = null;
}
```

For banners that fail to load, we recommend you to refresh the banner instead
of destroying and creating a new one. For details, see
[Refresh an ad](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/banner.md.txt#refresh_an_ad).

## Refresh an ad

If you configured your ad unit to refresh, you don't need to request another ad
when the ad fails to load. Google Mobile Ads Unity Plugin respects any refresh rate
you specified in the Ad Manager UI. If you haven't enabled
refresh, issue a new request. For more details on ad unit refresh, such as
setting a refresh rate, see

[Refresh rate for ads in mobile apps](https://support.google.com/admanager/answer/6022114).

> [!NOTE]
> **Note:** When setting a refresh rate in the Ad Manager UI, the automatic refresh occurs only if the banner is visible on screen.

## Banner sizes

Large adaptive banners provide a larger format designed for non-scrolling
layouts. Compared to standard anchored adaptive banners, these banners
allow a taller maximum height (up to 20% of screen height, between 50 and
150 dp). This increased space is optimized for video content.

The following table 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](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/banner/anchored-adaptive.md.txt) | Phones and Tablets | N/A |
| *Screen width* x 32\|50\|90 | [Smart banner](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/banner/smart.md.txt) | Phones and Tablets | `SMART_BANNER` |
| Learn more about [Adaptive Banners](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/banner/anchored-adaptive.md.txt), intended to replace [Smart Banners](https://developers.google.com/ad-manager/mobile-ads-sdk/unity/banner/smart.md.txt). ||||

> [!NOTE]
> **Note:** If an Android app tries to load a banner that's too big for its layout, the SDK won't display it, logging an error message instead.

## App events

App events let you create ads that can send messages to their app code. The app
can then take actions based on these messages.

You can listen for Ad Manager specific app events using [`AppEvent`](https://developers.google.com/admob/unity/reference/class/google-mobile-ads/api/ad-manager/app-event.md.txt). These events
can occur at any time during the ad's lifecycle, even before load is called.

`OnAppEventReceived` is raised when an app event occurs in an ad. Here is an
example of how to handle this event in your code:

```c#
adManagerBannerView.OnAppEventReceived += (AppEvent args) =>
{
    Debug.Log($"Received app event from the ad: {args.Name}, {args.Data}.");
};
```

Here is an example showing how to change the background color of your app
depending on an app event with a name of color:

```c#
adManagerBannerView.OnAppEventReceived += (AppEvent args) =>
{
    if (args.Name == "color")
    {
        Color color;
        if (ColorUtility.TryParseHtmlString(args.Data, out color))
        {
            renderer.material.color = color;
        }
    }
};
```

And, here is the corresponding creative that sends color app event:

```html
<html>
<head>
  <script src="//www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      // Send a color=green event when ad loads.
      admob.events.dispatchAppEvent("color", "green");

      document.getElementById("ad").addEventListener("click", function() {
        // Send a color=blue event when ad is clicked.
        admob.events.dispatchAppEvent("color", "blue");
      });
    });
  </script>
  <style>
    #ad {
      width: 320px;
      height: 50px;
      top: 0;
      left: 0;
      font-size: 24pt;
      font-weight: bold;
      position: absolute;
      background: black;
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="ad">Carpe diem!</div>
</body>
</html>

```

## Additional resources

- [HelloWorld example](https://github.com/googleads/googleads-mobile-unity/tree/main/samples/HelloWorld): A minimal implementation of all ad formats.