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
- Complete the Get started guide.
Realizar pruebas siempre con anuncios de prueba
El siguiente código de muestra contiene un ID de unidad de anuncios que puedes usar para solicitar anuncios de prueba. Se configuró especialmente para mostrar anuncios de prueba en lugar de anuncios de producción en cada solicitud, lo que hace que su uso sea seguro.
Sin embargo, después de registrar una app en la interfaz web deAd Manager y crear tus propios ID de unidades de anuncios para usar en la app, configura tu dispositivo como dispositivo de prueba de forma explícita durante el desarrollo.
/6499/example/banner
Inicializa el SDK de anuncios para dispositivos móviles
Antes de cargar anuncios, haz que tu app inicialice el SDK de anuncios para dispositivos móviles llamando a MobileAds.Initialize()
. Esto debe hacerse solo una vez, idealmente cuando se inicia la app.
using GoogleMobileAds;
using GoogleMobileAds.Api;
public class GoogleMobileAdsDemoScript : MonoBehaviour
{
public void Start()
{
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize((InitializationStatus initStatus) =>
{
// This callback is called once the MobileAds SDK is initialized.
});
}
}
Si usas mediación, espera hasta que se produzca la devolución de llamada antes de cargar anuncios, ya que esto garantizará que todos los adaptadores de mediación se inicialicen.
BannerView example
The sample code below details how to use the banner view. In the example, you
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
in a C# script attached to a GameObject
.
// This ad unit is configured to always serve test ads.
private string _adUnitId = "/6499/example/banner";
AdManagerBannerView _bannerView;
/// <summary>
/// Creates a 320x50 banner view at top of the screen.
/// </summary>
public void CreateBannerView()
{
Debug.Log("Creating banner view");
// If we already have a banner, destroy the old one.
if (_bannerView != null)
{
DestroyAd();
}
// Create a 320x50 banner at top of the screen
_bannerView = new AdManagerBannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
}
The constructor for a AdManagerBannerView
has the following
parameters:
adUnitId
: The ad unit ID from which theAdManagerBannerView
should load ads.AdSize
: The ad size you'd like to use. Consult Banner sizes for details.AdPosition
: The position where the banner views should be placed. TheAdPosition
enum lists the valid ad position values.
Note how different ad units are used, depending on the platform. You need to use an iOS ad unit for making ad requests on iOS and an Android ad unit for making requests on Android.
(Optional) Create a banner view with a custom position
For greater control over where a AdManagerBannerView
is
placed on screen than what's offered by AdPosition
values, use the constructor
that has x- and y-coordinates as parameters:
// Create a 320x50 banner views at coordinate (0,50) on screen.
_bannerView = new AdManagerBannerView(_adUnitId, AdSize.Banner, 0, 50);
The top-left corner of the AdManagerBannerView
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:
// Use the AdSize argument to set a custom size for the ad.
AdSize adSize = new AdSize(250, 250);
_bannerView = new AdManagerBannerView(_adUnitId, 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
:
var adView = new AdManagerBannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
adView.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 AdManagerAdRequest parameter which holds
runtime information, such as targeting info, exclusion labels, and the publisher
provided ID.
/// <summary>
/// Creates the banner view and loads a banner ad.
/// </summary>
public void LoadAd()
{
// create an instance of a banner view first.
if(_bannerView == null)
{
CreateAdManagerBannerView();
}
// create our request used to load the ad.
var adRequest = new AdManagerAdRequest();
// send the request to load the ad.
Debug.Log("Loading banner ad.");
_bannerView.LoadAd(adRequest);
}
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:
/// <summary>
/// listen to events the banner view may raise.
/// </summary>
private void ListenToAdEvents()
{
// Raised when an ad is loaded into the banner view.
_bannerView.OnBannerAdLoaded += () =>
{
Debug.Log("Banner view loaded an ad with response : "
+ _bannerView.GetResponseInfo());
};
// Raised when an ad fails to load into the banner view.
_bannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
{
Debug.LogError("Banner view failed to load an ad with error : "
+ error);
};
// Raised when the ad is estimated to have earned money.
_bannerView.OnAdPaid += (AdValue adValue) =>
{
Debug.Log(String.Format("Banner view paid {0} {1}.",
adValue.Value,
adValue.CurrencyCode));
};
// Raised when an impression is recorded for an ad.
_bannerView.OnAdImpressionRecorded += () =>
{
Debug.Log("Banner view recorded an impression.");
};
// Raised when a click is recorded for an ad.
_bannerView.OnAdClicked += () =>
{
Debug.Log("Banner view was clicked.");
};
// Raised when an ad opened full screen content.
_bannerView.OnAdFullScreenContentOpened += () =>
{
Debug.Log("Banner view full screen content opened.");
};
// Raised when the ad closed full screen content.
_bannerView.OnAdFullScreenContentClosed += () =>
{
Debug.Log("Banner view full screen content closed.");
};
}
Destroy the banner view
When finished using the banner view, be sure to call Destroy()
to release
resources.
/// <summary>
/// Destroys the banner view.
/// </summary>
public void DestroyBannerView()
{
if (_bannerView != null)
{
Debug.Log("Destroying banner view.");
_bannerView.Destroy();
_bannerView = null;
}
}
That's it! Your app is now ready to display banner ads.
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. |
Eventos de aplicaciones
Los eventos de aplicaciones le permiten crear anuncios que pueden enviar mensajes al código de esa aplicación. Luego, la app puede realizar acciones basadas en esos mensajes.
Puedes escuchar eventos de aplicaciones específicos de Ad Manager mediante AppEvent
. Estos eventos pueden ocurrir en cualquier momento durante el ciclo de vida del anuncio, incluso antes de que se llame a la carga.
namespace GoogleMobileAds.Api.AdManager;
/// The App event message sent from the ad.
public class AppEvent
{
// Name of the app event.
string Name;
// Argument passed from the app event.
string Value;
}
OnAppEventReceived
se genera cuando se produce un evento de aplicación en un anuncio. A continuación, se muestra un ejemplo de cómo controlar este evento en tu código:
_bannerview.OnAppEventReceived += (AppEvent args) =>
{
Debug.Log($"Received app event from the ad: {args.Name}, {args.Value}.");
};
A continuación, puedes ver un ejemplo en el que se muestra cómo cambiar el color de fondo de tu app según un evento de la app con un nombre de color:
_bannerview.OnAppEventReceived += (AppEvent args) =>
{
if (args.Name == "color")
{
Color color;
if (ColorUtility.TryParseColor(arg.Value, out color))
{
gameObject.GetComponent<Renderer>().material.color = color;
}
}
};
Y esta es la creatividad correspondiente que envía el evento de color de la app:
<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: 0px;
left: 0px;
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: A minimal implementation of all ad formats.