Unity LevelPlay
Ad Mediation
Unity C#
Mobile Game Monetization
Interstitial Ads
Banner Ads

Unity LevelPlay SDK Setup Guide: Interstitial & Banner Ads (2026)

29 min read
Eshan Naithani

Integrating a single ad network SDK directly into a mobile game is straightforward, but it leaves your monetization reliant on one demand source. If that network has no available campaign for a player's region or device—or bids a low price for an impression—you either lose the impression entirely or serve a low-value ad.

Unity LevelPlay (formerly ironSource Mediation, now part of Unity Grow) is an ad mediation platform that sits between your Unity client and multiple ad networks—such as Unity Ads, Google AdMob, AppLovin, Meta Audience Network, and Mintegral. Instead of calling each ad network separately, your game initializes a single LevelPlay SDK and requests ads through unified C# APIs while LevelPlay coordinates in-app bidding auctions and waterfall fallbacks across your connected demand sources.

This article is Part 1 of a 3-part technical series on Unity LevelPlay ad monetization:

(If you are only integrating standalone Unity Ads without multi-network mediation, see the Unity Ads Setup Guide instead.)

By following Part 1, you will install the modern Unity LevelPlay package (com.unity.services.levelplay), configure your App Keys and Ad Unit IDs, initialize the SDK using the Unity.Services.LevelPlay namespace, and build a reusable C# ad manager for interstitial and banner ads with proper event handling, safe-area support, and testing workflows.


Quick Start: What You'll Build

By the end of this guide, you will have a clean Unity LevelPlay integration covering five core components:

  1. LevelPlay SDK Installation: Installing the official Ads Mediation package (com.unity.services.levelplay) via Unity Package Manager and managing native dependencies with the LevelPlay Network Manager and Mobile Dependency Resolver.
  2. SDK Initialization: Registering LevelPlay.OnInitSuccess and LevelPlay.OnInitFailed listeners and initializing the SDK with platform-specific Android and iOS App Keys.
  3. Interstitial Integration: Creating a LevelPlayInterstitialAd instance, preloading ads, checking readiness and placement caps, handling display/load failures safely, and automatically preloading the next ad on close.
  4. Banner Integration: Configuring a LevelPlayBannerAd using LevelPlayBannerAd.Config.Builder with adaptive or standard sizing, Android safe-area support, show/hide controls, and proper cleanup (DestroyAd()) on scene teardown.
  5. Testing & Troubleshooting: Validating adapters on physical Android and iOS devices using LevelPlay.ValidateIntegration() and the built-in LevelPlay Test Suite.

Table of Contents

  1. What Is Unity LevelPlay?
  2. Prerequisites
  3. Installing the SDK
  4. Creating App Keys and Ad Units
  5. Initializing LevelPlay
  6. Implementing Interstitial Ads
  7. Implementing Banner Ads
  8. Testing on Android and iOS
  9. Common Errors and Troubleshooting
  10. Best Practices
  11. Frequently Asked Questions
  12. Next Steps

1. What Is Unity LevelPlay?

When you monetize a mobile game with ads, every ad opportunity (such as finishing a level or opening a menu) triggers an ad request. How that request is filled depends on whether you use a single ad network or an ad mediation layer.

Single Ad Network vs. Ad Mediation

ArchitectureHow Ad Requests WorkKey Trade-offs
Single Ad Network SDKYour client requests an ad from one network (for example, only Unity Ads or only AdMob).Simple initial setup, but limited to a single advertiser pool. Unfilled requests result in missed impressions, and there is no cross-network price competition.
Unity LevelPlay MediationYour client sends one request to LevelPlay, which queries multiple configured ad networks via in-app bidding and/or a waterfall.Requires configuring network adapters and dashboard credentials, but allows multiple networks to compete for each impression and provides fallback sources when one network cannot fill.

Core Mediation Concepts

Understanding four foundational terms will help you configure LevelPlay accurately:

  • In-App Bidding (Real-Time Bidding): In an in-app bidding auction, eligible demand sources compete for an ad opportunity. The winning bid is selected according to the mediation platform's auction rules, pricing and eligibility requirements.
  • Waterfall Mediation: Networks (or specific priced instances) are queried sequentially in descending order of historical or floor eCPM until an instance fills the request. Modern LevelPlay setups typically use a hybrid model combining real-time bidding with waterfall instances for networks that do not use bidding.
  • Fill Rate: The percentage of ad requests that successfully return a filled ad (Filled Ad Requests / Total Ad Requests × 100). When analyzing monetization metrics, distinguish between three separate stages of an ad's lifecycle:
    • Ad Requests: The total number of times your client (or mediation waterfall/auction) requests an ad from demand sources.
    • Filled Requests: The number of ad requests where a demand source successfully returns a playable ad creative to be cached.
    • Displayed Impressions: The number of filled ads that are actually shown on the player's screen (ShowAd() followed by OnAdDisplayed). Because preloaded ads are not always shown before a session ends, displayed impressions are typically lower than filled requests. Note that fill rate definitions can vary across advertising dashboards (some report request-level fill while others track opportunity-level fill), so always check the specific platform's measurement definitions when comparing results.
  • eCPM (Effective Cost Per Mille): The estimated revenue generated per 1,000 displayed ad impressions.

Note on Monetization Performance: Mediation does not guarantee fixed fill rates or automatic revenue multipliers. Actual eCPM and fill rate depend on player geography (Tier 1 vs. Tier 3 markets), game genre, ad placement timing, session length, user consent (GDPR / iOS ATT opt-in rates), and the specific demand networks active in your mediation group.


2. Prerequisites

Before writing C# integration code, verify your project environment:

  1. Unity Editor: Unity 2021.3 LTS, Unity 2022.3 LTS, or Unity 6 (6000.x) with Android and/or iOS Build Support installed.
  2. Unity Cloud / LevelPlay Account: Access to the Unity Cloud Dashboard (Grow > LevelPlay) to register your application and create Ad Units.
  3. Target SDK Version: The core initialization, interstitial, and banner examples in this guide target Unity LevelPlay SDK v9.0+ via the Ads Mediation package (com.unity.services.levelplay), using the Unity.Services.LevelPlay namespace. If you use the LevelPlayPrivacySettings API covered in Section 10, use SDK v9.5.0+ (or v9.4.x for dictionary-based GDPR consent).

Important — Upgrading from Older SDK Versions: Earlier versions of the SDK used the IronSource.Agent static class or the transitional com.unity3d.mediation namespace (which was deprecated in late v8.x and removed in v9.0+). If you are upgrading an existing project from an older .unitypackage or pre-9.0 installation, back up your settings, remove the legacy Assets/LevelPlay (or Assets/IronSource) and Assets/Mobile Dependency Resolver folders, and install com.unity.services.levelplay cleanly through the Unity Package Manager to avoid duplicate symbol errors.


3. Installing the SDK

Modern Unity LevelPlay integration uses the Unity Package Manager (UPM) rather than manually editing Gradle templates.

Step 1: Install the Ads Mediation Package (com.unity.services.levelplay)

  1. Open your project in the Unity Editor.
  2. Navigate to Window > Package Manager.
  3. Click the + button in the top-left corner and select Add package by name... (or search the Unity Registry for Ads Mediation).
  4. Enter com.unity.services.levelplay and click Add (or Install).

Step 2: Install Mobile Dependency Resolver (EDM4U)

When prompted by the LevelPlay package, allow it to import the External Dependency Manager for Unity (EDM4U / Mobile Dependency Resolver). EDM4U automatically resolves Android Gradle dependencies and iOS CocoaPods so you do not need to hardcode library versions into mainTemplate.gradle.

Step 3: Configure Network Adapters

  1. In the Unity Editor top menu bar, open Ads Mediation > Network Manager.
  2. Install or update the adapters for the ad networks you plan to mediate (Unity Ads and ironSource are typically included; you can add Google AdMob, AppLovin, Meta Audience Network, or Mintegral as needed).
  3. Open Ads Mediation > Developer Settings (or LevelPlay Mediate Settings) to configure platform-specific manifest entries—such as your Google AdMob Application ID if you enable the AdMob adapter, and the Android Advertising ID permission (com.google.android.gms.permission.AD_ID) for Android 13+ (API level 33+).
  4. For Android builds, run Assets > Mobile Dependency Resolver > Android Resolver > Resolve to verify that all adapter dependencies resolve cleanly. For iOS builds, EDM4U generates a Podfile during the Xcode export process, and the LevelPlay post-processor automatically appends required SKAdNetworkItems to Info.plist.

Official reference: Unity LevelPlay Package Integration Documentation


4. Creating App Keys and Ad Units

LevelPlay uses two distinct identifiers that you must configure per platform (Android and iOS):

  1. App Key: Identifies your application in the LevelPlay dashboard. Create separate Android and iOS apps in the dashboard (or link them from Unity Cloud) and copy each platform's unique App Key.
  2. Ad Unit ID: Identifies a specific ad format and placement group within your app (for example, an Interstitial ad unit and a Banner ad unit for Android, and corresponding Interstitial and Banner ad units for iOS).
IdentifierWhere to Find It in LevelPlay DashboardWhen It Is Used in C#
App KeySetup > Apps (listed per Android / iOS app)Passed once to LevelPlay.Init(appKey) at startup.
Interstitial Ad Unit IDSetup > Ad Units (Interstitial format)Passed to new LevelPlayInterstitialAd(adUnitId) after OnInitSuccess.
Banner Ad Unit IDSetup > Ad Units (Banner format)Passed to new LevelPlayBannerAd(adUnitId, config) after OnInitSuccess.

Keep your Android and iOS identifiers separate in your C# configuration so each platform build initializes with the matching credentials.


5. Initializing LevelPlay in C#

Before creating or loading any ad units, you must initialize the LevelPlay SDK and wait for the initialization callback.

Initialization Order of Operations

  1. Import the Namespace: Add using Unity.Services.LevelPlay; at the top of your script.
  2. Set Privacy & Regulation Flags (Pre-Init): If your game configures GDPR consent, US state privacy opt-outs (CCPA), or COPPA child-directed settings via LevelPlayPrivacySettings, configure them before calling LevelPlay.Init().
  3. Subscribe to Initialization Events: Register callbacks for LevelPlay.OnInitSuccess and LevelPlay.OnInitFailed.
  4. Call LevelPlay.Init(appKey): Pass the platform-specific App Key (and an optional custom user ID if you use server-to-server callbacks).
  5. Create Ad Objects in OnInitSuccess: Instantiate LevelPlayInterstitialAd and LevelPlayBannerAd only after OnInitSuccess fires.

Security & Logging Tip: Avoid printing full App Keys or sensitive user identifiers in production Debug.Log statements, as device logs on Android (logcat) can be read by external tools during debugging.


6. Implementing Interstitial Ads

Interstitial ads are full-screen interactive or video ads displayed at natural transition points. In the Unity.Services.LevelPlay API, interstitials are managed through an instance of LevelPlayInterstitialAd.

Interstitial Lifecycle

  1. Instantiate: After OnInitSuccess, create a single LevelPlayInterstitialAd(interstitialAdUnitId) instance. This instance is reusable across the session.
  2. Subscribe to Events:
    • OnAdLoaded(LevelPlayAdInfo adInfo): Fired when an ad is cached and ready to display.
    • OnAdLoadFailed(LevelPlayAdError error): Fired when no network could fill the request or a network error occurred.
    • OnAdDisplayed(LevelPlayAdInfo adInfo): Fired when the ad takes over the screen.
    • OnAdDisplayFailed(LevelPlayAdInfo adInfo, LevelPlayAdError error): Fired if a loaded ad fails to render when ShowAd() is called. (Note: In LevelPlay SDK v9.0+, this event passes (LevelPlayAdInfo, LevelPlayAdError). If you are on an earlier v8.x package prior to v9.0, check your package version as older 8.x releases used a LevelPlayAdDisplayInfoError wrapper).
    • OnAdClosed(LevelPlayAdInfo adInfo): Fired when the player dismisses the ad and returns to your game.
    • OnAdClicked(LevelPlayAdInfo adInfo) and OnAdInfoChanged(LevelPlayAdInfo adInfo): Optional events for click tracking and waterfall updates.
  3. Preload (LoadAd()): Call interstitialAd.LoadAd() early so the creative is already cached in memory before the player finishes a level.
  4. Verify Readiness & Show (IsAdReady() & ShowAd()): Always verify interstitialAd.IsAdReady() (and optionally !LevelPlayInterstitialAd.IsPlacementCapped(placementName)) before calling interstitialAd.ShowAd(placementName).
  5. Reload on Close: Inside OnAdClosed, call interstitialAd.LoadAd() so the next interstitial is preloaded for the following break.

Practical Guidance: When to Show Interstitial Ads

  • Use Natural Gameplay Breaks: Trigger interstitials only at clear transition boundaries—such as after a "Level Complete" summary screen, after a match ends, or when returning to the main menu.
  • Never Interrupt Active Gameplay: Showing an interstitial while a player is actively controlling a character or mid-puzzle causes immediate frustration, accidental clicks, and high churn.
  • Enforce Frequency Caps and Onboarding Grace Periods: Avoid showing interstitials during a player's first few minutes of onboarding. Combine LevelPlay dashboard pacing/capping rules with an in-game cooldown timer so back-to-back short levels do not trigger full-screen ads every 20 seconds.
  • Fail Safe on Unavailable Ads: If the player is offline or IsAdReady() returns false, never freeze the UI waiting for an ad. Proceed immediately to the next level or menu.

Official reference: Unity LevelPlay Interstitial Integration Documentation


7. Implementing Banner Ads

Banner ads are rectangular ad views anchored to the top or bottom of the screen. In Unity.Services.LevelPlay, banners are configured using LevelPlayBannerAd.Config.Builder and managed via LevelPlayBannerAd.

Practical Guidance: Banner Placement & Safe Areas

  • Top vs. Bottom Placement: LevelPlayBannerPosition.BottomCenter is the most common placement in portrait and landscape games, provided your bottom HUD buttons are offset above the banner height. Use TopCenter if the bottom of the screen is reserved for thumb swipe or drag controls.
  • Respect Safe Areas and Screen Cutouts: Calling .SetRespectSafeArea(true) on LevelPlayBannerAd.Config.Builder instructs the banner container on Android to position the banner inside the device's safe area so it does not overlap display cutouts or system navigation bars. Because SetRespectSafeArea is documented as an Android configuration option, you should also layout your Unity Canvas HUD within Screen.safeArea across both Android and iOS.
  • Adaptive vs. Fixed Banner Sizes:
    • LevelPlayAdSize.BANNER creates a standard 320x50 banner.
    • LevelPlayAdSize.CreateAdaptiveAdSize() creates a responsive banner that adapts to the device's screen width while maintaining an appropriate aspect ratio across phones and tablets.
  • Clean Up When Switching Scenes: Native banner views are rendered as platform UI overlays on top of the Unity surface. If you do not hide (HideAd()) or destroy (DestroyAd()) banners when unloading a scene, the banner overlay will remain visible across scenes. Note that once DestroyAd() is called on a LevelPlayBannerAd, that instance cannot be reloaded—you must instantiate a new LevelPlayBannerAd object if you want to load a banner again later.

Official reference: Unity LevelPlay Banner Integration Documentation


Complete C# Example: LevelPlayAdManager.cs

Below is a complete C# integration example targeting Unity LevelPlay SDK v9.0+ (com.unity.services.levelplay). It handles platform-specific configuration, initialization callbacks, interstitial preloading/showing with safe completion callbacks, banner configuration with safe-area support, and proper event unsubscription and ad destruction (DestroyAd()).

Verification Note: This script is written against the official Unity LevelPlay SDK v9.0+ API specification (Unity.Services.LevelPlay). Replace the placeholder App Keys and Ad Unit IDs with your own LevelPlay dashboard values and test on a physical Android or iOS build.

CSHARP
using System;
using UnityEngine;
using Unity.Services.LevelPlay;

public class LevelPlayAdManager : MonoBehaviour
{
    public static LevelPlayAdManager Instance { get; private set; }

    [Header("LevelPlay App Keys (Replace with Dashboard Values)")]
    [SerializeField] private string androidAppKey = "YOUR_ANDROID_APP_KEY";
    [SerializeField] private string iosAppKey = "YOUR_IOS_APP_KEY";

    [Header("Interstitial Ad Unit IDs")]
    [SerializeField] private string androidInterstitialAdUnitId = "YOUR_ANDROID_INTERSTITIAL_AD_UNIT_ID";
    [SerializeField] private string iosInterstitialAdUnitId = "YOUR_IOS_INTERSTITIAL_AD_UNIT_ID";

    [Header("Banner Ad Unit IDs")]
    [SerializeField] private string androidBannerAdUnitId = "YOUR_ANDROID_BANNER_AD_UNIT_ID";
    [SerializeField] private string iosBannerAdUnitId = "YOUR_IOS_BANNER_AD_UNIT_ID";

    [Header("Banner Settings")]
    [SerializeField] private bool useAdaptiveBanner = true;
    [SerializeField] private bool autoDisplayBannerOnLoad = true;
    [SerializeField] private float minSecondsBetweenInterstitials = 60f;

    [Header("Testing")]
    [SerializeField] private bool enableTestSuiteInDevelopmentBuilds = false;

    private LevelPlayInterstitialAd interstitialAd;
    private LevelPlayBannerAd bannerAd;

    private bool isInitialized;
    private bool isInitializing;
    private bool isLoadingInterstitial;
    private bool isShowingInterstitial;
    private float lastInterstitialShownTime = -999f;
    private Action pendingInterstitialCompleteCallback;

    private string ActiveAppKey
    {
        get
        {
#if UNITY_IOS
            return iosAppKey;
#elif UNITY_ANDROID
            return androidAppKey;
#else
            return androidAppKey;
#endif
        }
    }

    private string ActiveInterstitialAdUnitId
    {
        get
        {
#if UNITY_IOS
            return iosInterstitialAdUnitId;
#elif UNITY_ANDROID
            return androidInterstitialAdUnitId;
#else
            return androidInterstitialAdUnitId;
#endif
        }
    }

    private string ActiveBannerAdUnitId
    {
        get
        {
#if UNITY_IOS
            return iosBannerAdUnitId;
#elif UNITY_ANDROID
            return androidBannerAdUnitId;
#else
            return androidBannerAdUnitId;
#endif
        }
    }

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
        DontDestroyOnLoad(gameObject);
    }

    private void Start()
    {
        InitializeLevelPlay();
    }

    // =========================================================================
    // 1. SDK INITIALIZATION
    // =========================================================================

    public void InitializeLevelPlay()
    {
        if (isInitialized || isInitializing)
        {
            return;
        }

        string appKey = ActiveAppKey;
        if (string.IsNullOrWhiteSpace(appKey) || appKey.StartsWith("YOUR_"))
        {
            Debug.LogWarning("[LevelPlayAdManager] App Key is not configured for the current platform. Skipping initialization.");
            return;
        }

        isInitializing = true;

#if DEVELOPMENT_BUILD || UNITY_EDITOR
        if (enableTestSuiteInDevelopmentBuilds)
        {
            // Must be set before calling LevelPlay.Init
            LevelPlay.SetMetaData("is_test_suite", "enable");
        }
#endif

        LevelPlay.OnInitSuccess += OnLevelPlayInitSuccess;
        LevelPlay.OnInitFailed += OnLevelPlayInitFailed;

        Debug.Log("[LevelPlayAdManager] Initializing Unity LevelPlay SDK...");
        LevelPlay.Init(appKey);
    }

    private void OnLevelPlayInitSuccess(LevelPlayConfiguration configuration)
    {
        isInitializing = false;
        isInitialized = true;

        LevelPlay.OnInitSuccess -= OnLevelPlayInitSuccess;
        LevelPlay.OnInitFailed -= OnLevelPlayInitFailed;

        Debug.Log("[LevelPlayAdManager] LevelPlay SDK initialized successfully.");

        SetupInterstitialAd();
        SetupBannerAd();

#if DEVELOPMENT_BUILD
        if (enableTestSuiteInDevelopmentBuilds)
        {
            LevelPlay.LaunchTestSuite();
        }
#endif
    }

    private void OnLevelPlayInitFailed(LevelPlayInitError error)
    {
        isInitializing = false;
        isInitialized = false;

        LevelPlay.OnInitSuccess -= OnLevelPlayInitSuccess;
        LevelPlay.OnInitFailed -= OnLevelPlayInitFailed;

        Debug.LogError($"[LevelPlayAdManager] LevelPlay initialization failed. Code: {error?.ErrorCode}, Message: {error?.ErrorMessage}");
    }

    // =========================================================================
    // 2. INTERSTITIAL ADS
    // =========================================================================

    private void SetupInterstitialAd()
    {
        string adUnitId = ActiveInterstitialAdUnitId;
        if (string.IsNullOrWhiteSpace(adUnitId) || adUnitId.StartsWith("YOUR_"))
        {
            Debug.LogWarning("[LevelPlayAdManager] Interstitial Ad Unit ID is not configured.");
            return;
        }

        interstitialAd = new LevelPlayInterstitialAd(adUnitId);

        interstitialAd.OnAdLoaded += OnInterstitialAdLoaded;
        interstitialAd.OnAdLoadFailed += OnInterstitialAdLoadFailed;
        interstitialAd.OnAdDisplayed += OnInterstitialAdDisplayed;
        interstitialAd.OnAdDisplayFailed += OnInterstitialAdDisplayFailed;
        interstitialAd.OnAdClicked += OnInterstitialAdClicked;
        interstitialAd.OnAdClosed += OnInterstitialAdClosed;
        interstitialAd.OnAdInfoChanged += OnInterstitialAdInfoChanged;

        LoadInterstitialAd();
    }

    public void LoadInterstitialAd()
    {
        if (!isInitialized || interstitialAd == null)
        {
            return;
        }

        if (isLoadingInterstitial || isShowingInterstitial || interstitialAd.IsAdReady())
        {
            return;
        }

        isLoadingInterstitial = true;

        try
        {
            interstitialAd.LoadAd();
        }
        catch (Exception ex)
        {
            isLoadingInterstitial = false;
            Debug.LogError($"[LevelPlayAdManager] Exception while loading interstitial ad: {ex.Message}");
        }
    }

    /// <summary>
    /// Attempts to show an interstitial ad if ready, not already showing, and not on cooldown.
    /// Rejects duplicate concurrent requests and invokes their onComplete immediately so gameplay is never blocked.
    /// </summary>
    public void ShowInterstitialAd(string placementName = null, Action onComplete = null)
    {
        if (isShowingInterstitial)
        {
            Debug.LogWarning("[LevelPlayAdManager] Interstitial show already in progress. Rejecting duplicate request and continuing caller flow.");
            onComplete?.Invoke();
            return;
        }

        if (!isInitialized || interstitialAd == null)
        {
            onComplete?.Invoke();
            return;
        }

        if (Time.unscaledTime - lastInterstitialShownTime < minSecondsBetweenInterstitials)
        {
            Debug.Log("[LevelPlayAdManager] Interstitial skipped due to local cooldown timer.");
            onComplete?.Invoke();
            return;
        }

        if (!string.IsNullOrEmpty(placementName) && LevelPlayInterstitialAd.IsPlacementCapped(placementName))
        {
            Debug.Log($"[LevelPlayAdManager] Placement '{placementName}' is currently capped.");
            onComplete?.Invoke();
            return;
        }

        if (interstitialAd.IsAdReady())
        {
            isShowingInterstitial = true;
            pendingInterstitialCompleteCallback = onComplete;

            try
            {
                if (string.IsNullOrEmpty(placementName))
                {
                    interstitialAd.ShowAd();
                }
                else
                {
                    interstitialAd.ShowAd(placementName);
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[LevelPlayAdManager] Exception while showing interstitial ad: {ex.Message}");
                isShowingInterstitial = false;
                InvokePendingInterstitialCallback();
                LoadInterstitialAd();
            }
        }
        else
        {
            Debug.Log("[LevelPlayAdManager] Interstitial not ready. Requesting preload and continuing gameplay.");
            LoadInterstitialAd();
            onComplete?.Invoke();
        }
    }

    private void OnInterstitialAdLoaded(LevelPlayAdInfo adInfo)
    {
        isLoadingInterstitial = false;
        Debug.Log($"[LevelPlayAdManager] Interstitial loaded from network: {adInfo?.AdNetwork}");
    }

    private void OnInterstitialAdLoadFailed(LevelPlayAdError error)
    {
        isLoadingInterstitial = false;
        Debug.LogWarning($"[LevelPlayAdManager] Interstitial failed to load. Code: {error?.ErrorCode}, Message: {error?.ErrorMessage}");
    }

    private void OnInterstitialAdDisplayed(LevelPlayAdInfo adInfo)
    {
        lastInterstitialShownTime = Time.unscaledTime;
        Debug.Log("[LevelPlayAdManager] Interstitial displayed.");
    }

    private void OnInterstitialAdDisplayFailed(LevelPlayAdInfo adInfo, LevelPlayAdError error)
    {
        isShowingInterstitial = false;
        Debug.LogError($"[LevelPlayAdManager] Interstitial display failed. Code: {error?.ErrorCode}, Message: {error?.ErrorMessage}");
        InvokePendingInterstitialCallback();
        LoadInterstitialAd();
    }

    private void OnInterstitialAdClicked(LevelPlayAdInfo adInfo)
    {
        Debug.Log("[LevelPlayAdManager] Interstitial clicked.");
    }

    private void OnInterstitialAdClosed(LevelPlayAdInfo adInfo)
    {
        isShowingInterstitial = false;
        Debug.Log("[LevelPlayAdManager] Interstitial closed. Preloading next interstitial.");
        InvokePendingInterstitialCallback();
        LoadInterstitialAd();
    }

    private void OnInterstitialAdInfoChanged(LevelPlayAdInfo adInfo)
    {
        Debug.Log("[LevelPlayAdManager] Interstitial ad info updated.");
    }

    private void InvokePendingInterstitialCallback()
    {
        if (pendingInterstitialCompleteCallback != null)
        {
            Action callback = pendingInterstitialCompleteCallback;
            pendingInterstitialCompleteCallback = null;
            callback.Invoke();
        }
    }

    // =========================================================================
    // 3. BANNER ADS
    // =========================================================================

    private void SetupBannerAd()
    {
        string adUnitId = ActiveBannerAdUnitId;
        if (string.IsNullOrWhiteSpace(adUnitId) || adUnitId.StartsWith("YOUR_"))
        {
            Debug.LogWarning("[LevelPlayAdManager] Banner Ad Unit ID is not configured.");
            return;
        }

        LevelPlayAdSize adSize = useAdaptiveBanner
            ? LevelPlayAdSize.CreateAdaptiveAdSize()
            : LevelPlayAdSize.BANNER;

        var configBuilder = new LevelPlayBannerAd.Config.Builder()
            .SetSize(adSize)
            .SetPosition(LevelPlayBannerPosition.BottomCenter)
            .SetDisplayOnLoad(autoDisplayBannerOnLoad)
            // Applies on Android to avoid overlapping display cutouts and system bars
            .SetRespectSafeArea(true);

        LevelPlayBannerAd.Config bannerConfig = configBuilder.Build();
        bannerAd = new LevelPlayBannerAd(adUnitId, bannerConfig);

        bannerAd.OnAdLoaded += OnBannerAdLoaded;
        bannerAd.OnAdLoadFailed += OnBannerAdLoadFailed;
        bannerAd.OnAdDisplayed += OnBannerAdDisplayed;
        bannerAd.OnAdDisplayFailed += OnBannerAdDisplayFailed;
        bannerAd.OnAdClicked += OnBannerAdClicked;
        bannerAd.OnAdCollapsed += OnBannerAdCollapsed;
        bannerAd.OnAdExpanded += OnBannerAdExpanded;
        bannerAd.OnAdLeftApplication += OnBannerAdLeftApplication;

        bannerAd.LoadAd();
    }

    public void LoadBannerAd()
    {
        if (!isInitialized)
        {
            return;
        }

        // A destroyed LevelPlayBannerAd instance cannot be reused; create a new one if needed
        if (bannerAd == null)
        {
            SetupBannerAd();
            return;
        }

        bannerAd.LoadAd();
    }

    public void ShowBannerAd()
    {
        if (!isInitialized || bannerAd == null)
        {
            return;
        }

        bannerAd.ShowAd();
    }

    public void HideBannerAd()
    {
        if (bannerAd == null)
        {
            return;
        }

        bannerAd.HideAd();
    }

    public void DestroyBannerAd()
    {
        if (bannerAd == null)
        {
            return;
        }

        bannerAd.OnAdLoaded -= OnBannerAdLoaded;
        bannerAd.OnAdLoadFailed -= OnBannerAdLoadFailed;
        bannerAd.OnAdDisplayed -= OnBannerAdDisplayed;
        bannerAd.OnAdDisplayFailed -= OnBannerAdDisplayFailed;
        bannerAd.OnAdClicked -= OnBannerAdClicked;
        bannerAd.OnAdCollapsed -= OnBannerAdCollapsed;
        bannerAd.OnAdExpanded -= OnBannerAdExpanded;
        bannerAd.OnAdLeftApplication -= OnBannerAdLeftApplication;

        bannerAd.DestroyAd();
        bannerAd = null;
    }

    private void OnBannerAdLoaded(LevelPlayAdInfo adInfo)
    {
        Debug.Log($"[LevelPlayAdManager] Banner loaded from network: {adInfo?.AdNetwork}");
    }

    private void OnBannerAdLoadFailed(LevelPlayAdError error)
    {
        Debug.LogWarning($"[LevelPlayAdManager] Banner failed to load. Code: {error?.ErrorCode}, Message: {error?.ErrorMessage}");
    }

    private void OnBannerAdDisplayed(LevelPlayAdInfo adInfo)
    {
        Debug.Log("[LevelPlayAdManager] Banner displayed.");
    }

    private void OnBannerAdDisplayFailed(LevelPlayAdInfo adInfo, LevelPlayAdError error)
    {
        Debug.LogError($"[LevelPlayAdManager] Banner display failed. Code: {error?.ErrorCode}, Message: {error?.ErrorMessage}");
    }

    private void OnBannerAdClicked(LevelPlayAdInfo adInfo)
    {
        Debug.Log("[LevelPlayAdManager] Banner clicked.");
    }

    private void OnBannerAdCollapsed(LevelPlayAdInfo adInfo)
    {
        Debug.Log("[LevelPlayAdManager] Banner collapsed.");
    }

    private void OnBannerAdExpanded(LevelPlayAdInfo adInfo)
    {
        Debug.Log("[LevelPlayAdManager] Banner expanded.");
    }

    private void OnBannerAdLeftApplication(LevelPlayAdInfo adInfo)
    {
        Debug.Log("[LevelPlayAdManager] Banner click left application.");
    }

    // =========================================================================
    // 4. CLEANUP & AD DESTRUCTION
    // =========================================================================

    private void OnDestroy()
    {
        if (Instance == this)
        {
            Instance = null;
        }

        isShowingInterstitial = false;
        isLoadingInterstitial = false;
        pendingInterstitialCompleteCallback = null;

        LevelPlay.OnInitSuccess -= OnLevelPlayInitSuccess;
        LevelPlay.OnInitFailed -= OnLevelPlayInitFailed;

        if (interstitialAd != null)
        {
            interstitialAd.OnAdLoaded -= OnInterstitialAdLoaded;
            interstitialAd.OnAdLoadFailed -= OnInterstitialAdLoadFailed;
            interstitialAd.OnAdDisplayed -= OnInterstitialAdDisplayed;
            interstitialAd.OnAdDisplayFailed -= OnInterstitialAdDisplayFailed;
            interstitialAd.OnAdClicked -= OnInterstitialAdClicked;
            interstitialAd.OnAdClosed -= OnInterstitialAdClosed;
            interstitialAd.OnAdInfoChanged -= OnInterstitialAdInfoChanged;

            interstitialAd.DestroyAd();
            interstitialAd = null;
        }

        DestroyBannerAd();
    }
}

Attaching LevelPlayAdManager and Calling It from Gameplay

  1. Create a Bootstrap GameObject: In your initial startup or main menu scene, create an empty GameObject named LevelPlayAdManager and attach the LevelPlayAdManager.cs script. Because it calls DontDestroyOnLoad(gameObject), it persists across scene loads.
  2. Assign Inspector Credentials: Paste your Android and iOS App Keys and Ad Unit IDs into the serialized Inspector fields.
  3. Trigger an Interstitial at Level Complete: Call ShowInterstitialAd from your level completion handler and pass the scene transition inside the completion callback so the game progresses whether an ad is shown or skipped. Notice that LevelPlayAdManager tracks isShowingInterstitial and isLoadingInterstitial: if a second ShowInterstitialAd call occurs while an ad is already being displayed (for example, from a double-tap on a UI button), the duplicate request is rejected and its onComplete callback is invoked immediately without overwriting the active ad's pendingInterstitialCompleteCallback.
CSHARP
public void OnLevelCompleteContinueButtonClicked()
{
    if (LevelPlayAdManager.Instance != null)
    {
        LevelPlayAdManager.Instance.ShowInterstitialAd(
            placementName: "Level_Complete",
            onComplete: () => LoadNextLevelScene()
        );
    }
    else
    {
        LoadNextLevelScene();
    }
}
  1. Control Banner Visibility: Call LevelPlayAdManager.Instance.HideBannerAd() when entering full-screen cutscenes or heavy gameplay views, and LevelPlayAdManager.Instance.ShowBannerAd() when returning to menus.

8. Testing on Android and iOS

Testing ad mediation requires verifying both the C# callback flow and the native third-party network SDK adapters.

1. Unity Editor vs. Real Mobile Devices

In the Unity Editor Play Mode, LevelPlay provides simulated mock responses so you can verify that your C# events fire without throwing null-reference exceptions. However, third-party ad networks (such as AdMob, AppLovin, and Meta) use native Android .aar libraries and iOS .framework bundles that only execute on actual mobile operating systems. Always verify your integration on a physical Android or iOS device before release.

2. Validate Adapter Configuration (ValidateIntegration)

During development, you can call LevelPlay.ValidateIntegration() on a device build and inspect Android Logcat or the Xcode console. The integration helper prints a diagnostic table showing which network adapters are installed, whether their native SDK versions match, and whether required AndroidManifest.xml or Info.plist entries are valid.

3. Using the LevelPlay Test Suite

The LevelPlay Test Suite provides an interactive on-device UI overlay that lets you inspect every configured mediation network and test loading interstitial and banner creatives one network at a time:

  1. Enable the test suite metadata flag before calling LevelPlay.Init:
    CSHARP
    LevelPlay.SetMetaData("is_test_suite", "enable");
    
  2. Call LevelPlay.LaunchTestSuite() inside your OnInitSuccess callback.
  3. Register your test device's advertising ID (GAID on Android or IDFA on iOS) in the LevelPlay dashboard under Setup > Testing.
  4. Ensure you remove or disable the is_test_suite flag and LaunchTestSuite() call in production store builds.

4. How to Verify an Ad Request

To confirm that an ad request succeeded end-to-end on a device:

  • Confirm OnLevelPlayInitSuccess logs in Logcat (adb logcat -s Unity) or Xcode console.
  • Check that OnInterstitialAdLoaded or OnBannerAdLoaded fires and inspect adInfo.AdNetwork and adInfo.AdUnitId to see which network filled the request.
  • If OnAdLoadFailed fires, inspect error.ErrorCode and error.ErrorMessage to distinguish between a configuration issue (such as an invalid Ad Unit ID) and a normal "no-fill" response when no test campaign is active.

9. Common Errors and Troubleshooting

Symptom / ErrorLikely CauseResolution
namespace 'com.unity3d.mediation' could not be foundScript uses the deprecated pre-9.0 namespace.Replace using com.unity3d.mediation; with using Unity.Services.LevelPlay; and ensure com.unity.services.levelplay is installed in Package Manager.
OnInitFailed fires immediately on launchApp Key does not match the current build platform, or the device has no network connection.Verify that Android builds pass the Android App Key and iOS builds pass the iOS App Key. Implement a retry when network connectivity returns.
Ads fail to load when requested in Start()LoadAd() was called before LevelPlay.Init() finished initializing.Instantiate LevelPlayInterstitialAd and LevelPlayBannerAd and call LoadAd() inside the LevelPlay.OnInitSuccess callback.
Error Code 509: Show Fail: No ads to showShowAd() was called on an interstitial (or rewarded) ad unit when no ad was ready in memory (IsAdReady() was false, LoadAd() had not completed, or a previous LoadAd() failed).Always check interstitialAd.IsAdReady() before calling ShowAd(), wait for OnAdLoaded before attempting display, and call LoadAd() inside OnAdClosed so the next impression is preloaded.
OnAdLoadFailed fires (e.g., Error 510, Error 606, or No Fill)Distinguishes three different root causes during ad loading: (1) Genuine no-fill: demand networks have no active campaign inventory for the device/region (such as Error 606 on initial banner load), (2) Network connectivity problems or failed server responses (Error 510), or (3) Incorrect SDK / mediation configuration (mismatched Ad Unit IDs, missing network adapters, or unconfigured dashboard instances).Verify device internet connectivity, run LevelPlay.ValidateIntegration() to confirm adapters and manifest entries match your dashboard, register your device (GAID/IDFA) as a Test Device in the LevelPlay dashboard, and use the LevelPlay Test Suite to verify test creatives per network.
Banner remains on screen after changing scenesNative banner overlay persists independently of Unity scene unloads.Call bannerAd.HideAd() when leaving a scene or bannerAd.DestroyAd() when tearing down the banner controller.
Android build fails with duplicate class errorsLegacy Assets/IronSource or duplicate .jar/.aar files conflict with EDM4U packages.Delete legacy SDK folders, keep only com.unity.services.levelplay, and run Assets > Mobile Dependency Resolver > Android Resolver > Force Resolve.

Official reference: Unity LevelPlay Error Codes & Advanced Settings Documentation


10. Best Practices

Mobile ad networks require accurate privacy signals to comply with regional data protection laws and app store policies. Starting in LevelPlay SDK 9.4.0+, privacy flags are managed through the LevelPlayPrivacySettings class in the Unity.Services.LevelPlay namespace (replacing legacy LevelPlay.SetConsent and privacy SetMetaData strings used in SDK 9.3 and earlier).

Configuring LevelPlayPrivacySettings (SDK 9.5.0 and Newer)

In LevelPlay SDK 9.5.0+, use SetGDPRConsent, SetCCPA, and SetCOPPA to pass the user's resolved privacy state before initializing the SDK:

CSHARP
using Unity.Services.LevelPlay;

// Example only: use the user's actual consent choice
LevelPlayPrivacySettings.SetGDPRConsent(true);

// If the user has opted out of applicable data sharing
LevelPlayPrivacySettings.SetCCPA(true);

// If the application is child-directed
LevelPlayPrivacySettings.SetCOPPA(true);

Important: The snippet above shows the API syntax for each setting—do not hardcode all three flags to true in production. Each call must reflect the actual user's consent choice, opt-out preference, and your application's audience classification.

Version Differences Across SDK 9.3, 9.4, and 9.5+

  • LevelPlay SDK 9.5.0+: Supports the global boolean LevelPlayPrivacySettings.SetGDPRConsent(bool) method alongside SetCCPA(bool) and SetCOPPA(bool).
  • LevelPlay SDK 9.4.x: Introduced LevelPlayPrivacySettings.SetCCPA(bool) and LevelPlayPrivacySettings.SetCOPPA(bool), while GDPR consent is configured per network using a dictionary via SetGDPRConsents:
    CSHARP
    LevelPlayPrivacySettings.SetGDPRConsents(
        new Dictionary<string, bool>
        {
            { "UnityAds", true },
            { "AdMob", true }
        }
    );
    
    (Note: In SDK 9.4.x, each call to SetGDPRConsents replaces previously stored network consents, so the dictionary must reflect the user's actual preferences across your configured networks.)
  • LevelPlay SDK 9.3 and earlier: Used legacy LevelPlay.SetConsent(bool) and LevelPlay.SetMetaData(...) calls, which are deprecated in SDK 9.4+.

Key Implementation Guidelines

  • Pass Consent Collected by Your CMP: In the EEA, UK, and other regulated regions, collect user choices using a certified Consent Management Platform (CMP) such as Google UMP. If your CMP supports the IAB TCF v2.2 / Google Additional Consent specification, LevelPlay and supported adapters can read the stored consent string automatically, or you can forward the user's resolved choice via LevelPlayPrivacySettings.
  • Configure Settings Before LevelPlay.Init(): Always apply LevelPlayPrivacySettings (and on iOS 14.5+, request the ATTrackingManager App Tracking Transparency prompt) before calling LevelPlay.Init(appKey). This ensures LevelPlay and all mediated network adapters initialize with the correct regulatory restrictions from the very first ad request.
  • Handle Consent Withdrawal: Provide an accessible "Privacy Settings" option in your game's settings menu so players can review or withdraw consent at any time. When a user updates or revokes consent, immediately pass the updated boolean (false on withdrawal) to LevelPlayPrivacySettings.SetGDPRConsent (or SetGDPRConsents in 9.4.x) and update SetCCPA if they opt out of data sharing.
  • Set COPPA Based on Your Target Audience: LevelPlayPrivacySettings.SetCOPPA(true) should only be enabled if your game is directed at children under COPPA (or for users identified as children through a neutral age screen in a mixed-audience app). General-audience games that do not target children should not set SetCOPPA(true), as child-directed mode disables personalized advertising and behavioral identifiers across mediated networks.

Refer to the official Unity LevelPlay Regulation & Advanced Settings Documentation for complete regulatory details.

2. Combine Ads with In-App Purchases ("Remove Ads")

Players who spend money on In-App Purchases (IAP) generally expect an uninterrupted experience. When a player purchases a non-consumable "Remove Ads" pack or any store bundle, call DestroyBannerAd() and bypass ShowInterstitialAd() calls while keeping optional rewarded ads available. For a complete store implementation, see the Unity IAP Setup Guide.

3. Protect Frame Rate and Memory Budget

Mediation adapters initialize native views and cache video assets in memory. Avoid initializing or loading multiple heavy ad formats simultaneously during CPU-intensive gameplay frames. Preload interstitials during loading screens or right after an ad closes, and profile your device memory footprint on low-end Android hardware. For detailed CPU, UI Canvas, and RAM profiling techniques, read the Unity Mobile Optimization Guide.


11. Frequently Asked Questions

What is the correct package and namespace for Unity LevelPlay in 2026?

Use the Ads Mediation package (com.unity.services.levelplay) from the Unity Package Manager and import the Unity.Services.LevelPlay namespace in your C# scripts. Older namespaces such as com.unity3d.mediation and legacy IronSource.Agent static methods are deprecated in LevelPlay SDK v9.0+.

Can I create LevelPlayInterstitialAd or LevelPlayBannerAd objects in Awake() or Start()?

No. You should instantiate LevelPlayInterstitialAd and LevelPlayBannerAd objects only after the SDK fires the LevelPlay.OnInitSuccess callback. Creating or loading ad units before initialization completes can result in failed requests or uninitialized adapter states.

Why do ads show a mock placeholder in the Unity Editor instead of real network creatives?

Third-party ad network SDKs (such as AdMob, AppLovin, and Meta Audience Network) rely on native Android (Java/Kotlin) and iOS (Objective-C/Swift) libraries. The Unity Editor only simulates callback flow with placeholder UI. To test real mediated creatives and adapter bidding, build and deploy to a physical Android or iOS device.

How do I prevent banner ads from overlapping mobile safe areas?

When building your LevelPlayBannerAd.Config, call .SetRespectSafeArea(true) on the LevelPlayBannerAd.Config.Builder. According to official Unity LevelPlay documentation, SetRespectSafeArea applies on Android to prevent banners from overlapping display cutouts and system bars. Across both Android and iOS, also anchor your Unity Canvas HUD within Screen.safeArea with a bottom or top margin so interactive gameplay buttons are never covered by the banner container.

What should happen in gameplay if an interstitial ad fails to load or is not ready?

Your game should never block level progression waiting for an ad. Always check interstitialAd.IsAdReady() before calling ShowAd(). If the ad is not ready—or if OnAdDisplayFailed fires—trigger a background LoadAd() call and immediately continue to the next scene or menu.

Do I need to manually add Google Play Services dependencies to mainTemplate.gradle?

In standard setups using com.unity.services.levelplay, manual edits to mainTemplate.gradle are not required. The LevelPlay Network Manager works alongside the Mobile Dependency Resolver (EDM4U) to inject the exact Android Gradle dependencies and iOS CocoaPods specified by your installed network adapters.


12. Next Steps: Part 2 and Part 3

With the Unity LevelPlay SDK initialized and your interstitial and banner ad units running cleanly, you are ready to implement rewarded video ads and configure multi-network mediation in the next installments of this series:

Need help integrating Unity LevelPlay or optimizing mobile game monetization? I help game studios build, integrate, and optimize Unity monetization systems.

Share this article

Get Practical Unity Development Insights

Technical guides on Unity performance, AI gameplay systems, mobile monetization, and game development.

Unsubscribe at any time. Your data is never shared.

Recommended Reading

More articles in Game Monetization