Unity Interstitial Ads Integration Tutorial
In this tutorial, you will learn how to integrate interstitial ads into your Unity project using the Google Mobile Ads SDK. Interstitial ads are full-screen ads displayed at natural transition points in your app, such as between levels of a game. Below is the complete C# script with detailed explanations and a "Copy Code" button for easy use.
Step-by-Step Explanation
- Initialize the SDK: The
MobileAds.Initialize
method initializes the Google Mobile Ads SDK. - Load an Interstitial Ad: The
LoadInterstitialAd
method handles ad requests and ensures that ads are ready for display. - Show the Ad: The
ShowInterstitialAd
method checks if an ad is ready before showing it to the user. - Event Handlers: Ad lifecycle events like impressions, clicks, and fullscreen closures are logged and handled.
- Reload on Close: The
RegisterReloadHandler
ensures a new ad loads after the previous one closes.
Unity C# Script
using UnityEngine;
using GoogleMobileAds.Api;
using System;
public class InterstitialAdManager : MonoBehaviour
{
public string InterstitialID = "";
private InterstitialAd _interstitialAd;
void Start()
{
MobileAds.Initialize((InitializationStatus initStatus) =>
{
LoadInterstitialAd();
});
Invoke("AutoShowAd", 5f);
}
public void LoadInterstitialAd()
{
if (_interstitialAd != null)
{
_interstitialAd.Destroy();
_interstitialAd = null;
}
Debug.Log("Loading the interstitial ad.");
var adRequest = new AdRequest();
InterstitialAd.Load(InterstitialID, adRequest,
(InterstitialAd ad, LoadAdError error) =>
{
if (error != null || ad == null)
{
Debug.LogError("Interstitial ad failed to load: " + error);
return;
}
Debug.Log("Interstitial ad loaded.");
_interstitialAd = ad;
RegisterEventHandlers(_interstitialAd);
});
}
public void ShowInterstitialAd()
{
if (_interstitialAd != null && _interstitialAd.CanShowAd())
{
Debug.Log("Showing interstitial ad.");
_interstitialAd.Show();
}
else
{
Debug.LogError("Interstitial ad is not ready yet.");
}
}
private void RegisterEventHandlers(InterstitialAd interstitialAd)
{
interstitialAd.OnAdPaid += (AdValue adValue) =>
{
Debug.Log($"Ad paid {adValue.Value} {adValue.CurrencyCode}.");
};
interstitialAd.OnAdImpressionRecorded += () =>
{
Debug.Log("Ad impression recorded.");
};
interstitialAd.OnAdClicked += () =>
{
Debug.Log("Ad clicked.");
};
interstitialAd.OnAdFullScreenContentOpened += () =>
{
Debug.Log("Ad opened fullscreen content.");
};
interstitialAd.OnAdFullScreenContentClosed += () =>
{
Debug.Log("Ad closed fullscreen content.");
LoadInterstitialAd();
};
}
}
Copy the script above, replace InterstitialID
with your Ad Unit ID, and attach the script to a GameObject in Unity to enable interstitial ads in your project.