Adding an AdMob app open ad to a Unity app

1. Introduction

In this codelab, you implement an AdMob app open ad in a Unity app.

What you'll build

This codelab guides you through implementing an AdMob app open ad in a Unity app using the Google Mobile Ads Unity plugin.

6338548c3f73e7cf.gif

If you have any issues (code bugs, grammatical errors, unclear wording, and so on) as you work through this codelab, report the issue using the Report a mistake link in the lower, left corner of the codelab.

What you'll learn

  • How to configure the Google Mobile Ads Unity plugin
  • How to implement an app open ad in a Unity app

What you'll need

  • Unity 2018.4 or later
  • Xcode 12 or later and CocoaPods (to deploy to iOS)

How would you rate your level of experience with AdMob?

Novice Intermediate Proficient

2. Set up the development environment

Download the code

After you download the zip file, extract its contents. You will have a folder named admob-appopen-unity-main.

Alternatively, you can clone the GitHub repository from the command line:

$ git clone https://github.com/googlecodelabs/admob-appopen-unity

The repository contains two folders:

  • android_studio_folder.png starter: Starting code that you will build in this codelab.
  • android_studio_folder.png complete: Completed code for this codelab.

3. Set up AdMob app and ad units

Because Unity is a multi-platform SDK, you need to add an app and ad units for both Android and iOS in AdMob.

Set up for Android

To set up for Android, you need to add an Android app and create ad units.

Add an Android app

  1. In the AdMob console, click ADD APP from the Apps menu.
  2. Select Android as the platform. When you're asked Is the app listed on a supported app store?, click NO.
  3. Enter AdMob app open ad in the app name field.
  4. Enabling user metrics is not necessary to complete this codelab. However, we recommend that you do because it allows you to understand user behavior in more detail. Click ADD to complete the process.

Create an ad unit

  1. Select AdMob app open ad app (Android) from Apps menu in the AdMob console.
  2. Click the Ad units menu.

  1. Click ADD AD UNIT.
  2. Select App open as the format.
  3. Enter android-appopen in the Ad unit name field.
  4. Click CREATE AD UNIT to complete the process.

It usually takes a few hours for a new ad unit to be able to serve ads.

If you want to test the ad's behavior immediately, then use the test app ID and ad unit IDs listed in the Android app ID/ad unit ID and iOS app ID/ad unit ID tables.

Set up for iOS

To set up for iOS, you need to add an iOS app and create ad units.

Add an iOS app

  1. In the AdMob console, click ADD APP from the Apps menu.
  2. Select iOS as the platform. When you're asked Is the app listed on a supported app store?, click NO.
  3. Enter AdMob app open ad in the app name field.
  4. Enabling user metrics is not necessary to complete this codelab. However, we recommend that you do because it allows you to understand user behavior in more detail. Click ADD to complete the process.

Create an ad unit

  1. Select AdMob inline ads app (iOS) from Apps menu in the AdMob console.
  2. Click the Ad units menu.

  1. Click ADD AD UNIT.
  2. Select App open as the format.
  3. Enter ios-appopen in the Ad unit name field.
  4. Click CREATE AD UNIT to complete the process.

It usually takes a few hours for a new ad unit to be able to serve ads.

If you want to test the ad's behavior immediately, then use the test app ID and ad unit IDs listed in the following table.

Optional: Use the test AdMob app and ad units

If you want to follow the codelab instead of creating a new application and ad units on your own, you can use the test AdMob app ID and ad unit IDs listed in the following tables.

Android app ID/ad unit ID

Item

app ID/ad unit ID

AdMob app ID

ca-app-pub-3940256099942544~3347511713

Ad unit ID

ca-app-pub-3940256099942544/3419835294

iOS app ID/ad unit ID

Item

app ID/ad unit ID

AdMob app ID

ca-app-pub-3940256099942544~1458002511

Ad unit ID

ca-app-pub-3940256099942544/5662855259

For more information about the test ads, see the Android test ads and the iOS test ads developer documentation.

4. Add the Google Mobile Ads Unity plugin

Integrating the Google Mobile Ads Unity plugin is the first step toward displaying AdMob ads and earning revenue.

Download the Mobile Ads Unity plugin

The Google Mobile Ads Unity plugin enables Unity developers to easily serve Google Mobile Ads on Android and iOS apps. The plugin provides a C# interface for requesting ads that is used by C# scripts in your Unity project.

Use the link below to download the Unity package for the plugin.

Open the starter project

  1. Launch Unity Hub.
  2. In Projects tab, click ADD button.
  3. Navigate to the folder where you extracted the downloaded code in the Set up development environment step.
  4. Open starter folder.
  5. You'll see the starter project in the project list. Click the project to open it in Unity Editor.

Import the Mobile Ads Unity plugin

  1. In the Unity editor, select Assets > Import Package > Custom Package from the menu.
  2. Select the GoogleMobileAds-{VERSION}.unitypackage you downloaded in the previous step.
  3. Make sure all of the files are selected and click Import.

Set your AdMob app ID

  1. In the Unity Editor, select Assets > Google Mobile Ads > Settings from the menu.
  2. Enter your Android and iOS AdMob app ID in each field. If you want to follow the codelab instead of creating a new application and ad units on your own, enter the test AdMob app ID as follows.

8890521e199b1090.png

5. Create a utility class

Create a new class called AppOpenAdManager under Scripts folder. This class manages an instance variable to keep track of a loaded ad and the ad unit ID for each platform.

AppOpenAdManager.cs

using System;
using GoogleMobileAds.Api;
using UnityEngine;

public class AppOpenAdManager
{
#if UNITY_ANDROID
    // Test ad unit ID: ca-app-pub-3940256099942544/3419835294
    private const string AD_UNIT_ID = "<YOUR_ANDROID_APPOPEN_AD_UNIT_ID>";
#elif UNITY_IOS
    // Test ad unit ID: ca-app-pub-3940256099942544/5662855259
    private const string AD_UNIT_ID = "<YOUR_IOS_APPOPEN_AD_UNIT_ID>";
#else
    private const string AD_UNIT_ID = "unexpected_platform";
#endif

    private static AppOpenAdManager instance;

    private AppOpenAd ad;

    private bool isShowingAd = false;

    public static AppOpenAdManager Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new AppOpenAdManager();
            }

            return instance;
        }
    }

    private bool IsAdAvailable
    {
        get
        {
            return ad != null;
        }
    }

    public void LoadAd()
    {
        // TODO: Load an app open ad.
    }
}

Load an ad

Loading an ad is accomplished using the static AppOpenAd.LoadAd() method. The load method requires an ad unit ID, a ScreenOrientation mode, an AdRequest object, and a completion handler which gets called when ad loading succeeds or fails.

The loaded AppOpenAd object is provided as a parameter in the completion handler. Implement the LoadAd() method as follows.

AppOpenAdManager.cs

public class AppOpenAdManager
{
    ...

    public void LoadAd()
    {
        AdRequest request = new AdRequest.Builder().Build();

        // Load an app open ad for portrait orientation
        AppOpenAd.LoadAd(AD_UNIT_ID, ScreenOrientation.Portrait, request, ((appOpenAd, error) =>
        {
            if (error != null)
            {
                // Handle the error.
                Debug.LogFormat("Failed to load the ad. (reason: {0})", error.LoadAdError.GetMessage());
                return;
            }

            // App open ad is loaded.
            ad = appOpenAd;
        }));
    }
}

Show the ad

Before showing the ad, register for each event handler to listen to each ad event.

AppOpenAdManager.cs

public class AppOpenAdManager
{
    ...

    public void ShowAdIfAvailable()
    {
        if (!IsAdAvailable || isShowingAd)
        {
            return;
        }

        ad.OnAdDidDismissFullScreenContent += HandleAdDidDismissFullScreenContent;
        ad.OnAdFailedToPresentFullScreenContent += HandleAdFailedToPresentFullScreenContent;
        ad.OnAdDidPresentFullScreenContent += HandleAdDidPresentFullScreenContent;
        ad.OnAdDidRecordImpression += HandleAdDidRecordImpression;
        ad.OnPaidEvent += HandlePaidEvent;

        ad.Show();
    }

    private void HandleAdDidDismissFullScreenContent(object sender, EventArgs args)
    {
        Debug.Log("Closed app open ad");
        // Set the ad to null to indicate that AppOpenAdManager no longer has another ad to show.
        ad = null;
        isShowingAd = false;
        LoadAd();
    }

    private void HandleAdFailedToPresentFullScreenContent(object sender, AdErrorEventArgs args)
    {
        Debug.LogFormat("Failed to present the ad (reason: {0})", args.AdError.GetMessage());
        // Set the ad to null to indicate that AppOpenAdManager no longer has another ad to show.
        ad = null;
        LoadAd();
    }

    private void HandleAdDidPresentFullScreenContent(object sender, EventArgs args)
    {
        Debug.Log("Displayed app open ad");
        isShowingAd = true;
    }

    private void HandleAdDidRecordImpression(object sender, EventArgs args)
    {
        Debug.Log("Recorded ad impression");
    }

    private void HandlePaidEvent(object sender, AdValueEventArgs args)
    {
        Debug.LogFormat("Received paid event. (currency: {0}, value: {1}",
                args.AdValue.CurrencyCode, args.AdValue.Value);
    }
}

Consider ad expiration

Ad references in the app open will time out after four hours. Ads rendered more than four hours after request time will no longer be valid and may not earn revenue.

To ensure you don't show an expired ad, modify IsAdAvailable property to the AppOpenAdManager that checks how long it has been since your ad loaded. Then, use that method to check if the ad is still valid.

AppOpenAdManager.cs

public class AppOpenAdManager
{
    ...

    // TODO: Add loadTime field
    private DateTime loadTime;

    private bool IsAdAvailable
    {
        get
        {
            // TODO: Consider ad expiration
            return ad != null && (System.DateTime.UtcNow - loadTime).TotalHours < 4;
        }
    }

    public void LoadAd()
    {
        if (IsAdAvailable)
        {
            return;
        }

        AdRequest request = new AdRequest.Builder().Build();
        AppOpenAd.LoadAd(AD_UNIT_ID, ScreenOrientation.Portrait, request, ((appOpenAd, error) =>
        {
            if (error != null)
            {
                Debug.LogFormat("Failed to load the ad. (reason: {0})", error.LoadAdError.GetMessage());
                return;
            }

            ad = appOpenAd;
            Debug.Log("App open ad loaded");

            // TODO: Keep track of time when the ad is loaded.
            loadTime = DateTime.UtcNow;
        }));
    }
}

6. Update the scene to load/show the ad

Update Start() method in MainScene class to load an app open ad when the scene starts.

In order to be notified of app foregrounding events, we recommend listening to the AppStateEventNotifier singleton. By implementing the AppStateEventNotifier.AppStateChanged delegate, your app will be alerted to app launch and foregrounding events and will be able to show the ad.

MainScene.cs

using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
using UnityEngine;

public class MainScene : MonoBehaviour
{
    public void Start()
    {
        // TODO: Request an app open ad.
        MobileAds.Initialize((initStatus) =>
        {
            AppOpenAdManager.Instance.LoadAd();
            AppStateEventNotifier.AppStateChanged += OnAppStateChanged;
        });
    }

    public void OnAppStateChanged(AppState state)
    {
        if (state == AppState.Foreground)
        {
            // TODO: Show an app open ad if available.
            AppOpenAdManager.Instance.ShowAdIfAvailable();
        }
    }
}

That's it! Build and run the project on a device or an emulator. Once the app is launched, wait for a few seconds to allow the ad to be fully loaded.

After then, once you switch back to the app from other apps/home screen, the app open ad will be displayed as below.

6338548c3f73e7cf.gif

7. All done!

You completed the codelab. You can find the completed code for this codelab in the android_studio_folder.pngcomplete folder.