Unity LevelPlay
Rewarded Video
Ad Mediation
AdMob
AppLovin
Mobile Monetization

Unity Ad Monetization Guide using Unity LevelPlay: Rewarded Ads & Network Mediation (Part 2)

8 min read
Eshan Naithani

Welcome to Part 2 of our 3-Part Unity LevelPlay Ad Monetization Masterclass:

In this second installment, we focus on Rewarded Video Ads using the modern Unity LevelPlay SDK v9.0+ (com.unity.services.levelplay, namespace Unity.Services.LevelPlay). We cover LevelPlayRewardedAd lifecycle management, event cleanup, duplicate reward prevention, Server-to-Server (S2S) reward validation, and third-party network adapter setup.


1. Rewarded Video Architecture & Reward Validation

Rewarded ads let players opt in to watch a video ad in exchange for an in-game reward (such as extra lives, revives, or soft currency).

Client-Side vs. Server-to-Server (S2S) Validation

  • Client-Side Callbacks (OnAdRewarded): The LevelPlay SDK fires OnAdRewarded locally when the ad network confirms completion. Suitable for offline-first casual games with local economies, provided you guard against duplicate callback grants.
  • Server-to-Server (S2S) Callbacks: LevelPlay's servers send an HTTP GET request to your backend endpoint with signed query parameters (userid, rewards, eventId, timestamp, signature) once the ad completes. Your backend verifies the MD5 signature against your LevelPlay Private Key and enforces eventId idempotency before crediting the player's server-side balance.

2. Production-Structured C# Rewarded Ad Controller (LevelPlayRewardedAd)

This production-structured C# example demonstrates proper Unity.Services.LevelPlay namespace usage, named event handlers with full OnDestroy cleanup, Dispose() lifecycle management, display-failure recovery, and client-side duplicate reward prevention.

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

public class LevelPlayRewardedManager : MonoBehaviour
{
    [Header("LevelPlay Ad Unit ID")]
    [SerializeField] private string rewardedAdUnitId = "YOUR_REWARDED_AD_UNIT_ID";

    private LevelPlayRewardedAd rewardedAd;
    private readonly HashSet<string> processedAuctionIds = new HashSet<string>();
    private bool rewardGrantedForCurrentShow;
    private bool isInitialized;

    private void OnEnable()
    {
        LevelPlay.OnInitSuccess += OnSdkInitSuccess;
    }

    private void OnDisable()
    {
        LevelPlay.OnInitSuccess -= OnSdkInitSuccess;
    }

    private void OnSdkInitSuccess(LevelPlayConfiguration config)
    {
        if (isInitialized) return;
        isInitialized = true;
        SetupRewardedAd();
    }

    private void SetupRewardedAd()
    {
        rewardedAd = new LevelPlayRewardedAd(rewardedAdUnitId);

        rewardedAd.OnAdLoaded += OnRewardedAdLoaded;
        rewardedAd.OnAdLoadFailed += OnRewardedAdLoadFailed;
        rewardedAd.OnAdDisplayed += OnRewardedAdDisplayed;
        rewardedAd.OnAdDisplayFailed += OnRewardedAdDisplayFailed;
        rewardedAd.OnAdClicked += OnRewardedAdClicked;
        rewardedAd.OnAdRewarded += OnRewardedAdRewarded;
        rewardedAd.OnAdClosed += OnRewardedAdClosed;

        rewardedAd.LoadAd();
    }

    public void ShowRewardedAd(string playerId = null, string placementName = null)
    {
        if (rewardedAd == null || !rewardedAd.IsAdReady())
        {
            Debug.LogWarning("[LevelPlay Rewarded] Ad is not ready yet.");
            return;
        }

        // Required for S2S callbacks: set a 1-64 char alphanumeric user ID BEFORE ShowAd()
        if (!string.IsNullOrEmpty(playerId))
        {
            LevelPlay.SetDynamicUserId(playerId);
        }

        rewardGrantedForCurrentShow = false;

        if (!string.IsNullOrEmpty(placementName))
        {
            rewardedAd.ShowAd(placementName);
        }
        else
        {
            rewardedAd.ShowAd();
        }
    }

    private void OnRewardedAdLoaded(LevelPlayAdInfo adInfo)
    {
        // Note: adInfo.Revenue is estimated per-impression revenue in USD (not eCPM).
        // Estimated eCPM = Revenue * 1000.
        double impressionRevenueUsd = adInfo.Revenue ?? 0d;
        Debug.Log(
            $"[LevelPlay Rewarded] Loaded ({adInfo.AdUnitId}). " +
            $"Est. Impression Revenue: ${impressionRevenueUsd:F6} USD"
        );
    }

    private void OnRewardedAdLoadFailed(LevelPlayAdError error)
    {
        Debug.LogError($"[LevelPlay Rewarded] Load failed ({error.ErrorCode}): {error.ErrorMessage}");
    }

    private void OnRewardedAdDisplayed(LevelPlayAdInfo adInfo)
    {
        Debug.Log($"[LevelPlay Rewarded] Displayed from network: {adInfo.AdNetwork}");
    }

    private void OnRewardedAdDisplayFailed(LevelPlayAdInfo adInfo, LevelPlayAdError error)
    {
        Debug.LogError($"[LevelPlay Rewarded] Display failed ({error.ErrorCode}): {error.ErrorMessage}");
        rewardedAd?.LoadAd();
    }

    private void OnRewardedAdClicked(LevelPlayAdInfo adInfo)
    {
        Debug.Log("[LevelPlay Rewarded] Ad clicked.");
    }

    private void OnRewardedAdRewarded(LevelPlayAdInfo adInfo, LevelPlayReward reward)
    {
        // Duplicate-reward prevention: guard by current show state AND auction ID
        if (rewardGrantedForCurrentShow)
        {
            Debug.LogWarning("[LevelPlay Rewarded] Duplicate OnAdRewarded ignored for current show.");
            return;
        }

        string auctionId = adInfo?.AuctionId;
        if (!string.IsNullOrEmpty(auctionId) && !processedAuctionIds.Add(auctionId))
        {
            Debug.LogWarning($"[LevelPlay Rewarded] Duplicate auctionId '{auctionId}' ignored.");
            return;
        }

        rewardGrantedForCurrentShow = true;
        Debug.Log($"[LevelPlay Rewarded] Granting {reward.Amount} x {reward.Name}");
        GrantLocalRewardPlaceholder(reward.Name, reward.Amount);
    }

    private void OnRewardedAdClosed(LevelPlayAdInfo adInfo)
    {
        rewardGrantedForCurrentShow = false;
        rewardedAd?.LoadAd();
    }

    /// <summary>
    /// Illustrative local-only reward handler. For online economies, do not credit
    /// currency directly from PlayerPrefs—wait for verified S2S backend confirmation.
    /// </summary>
    private void GrantLocalRewardPlaceholder(string rewardType, int amount)
    {
        string key = rewardType == "Gems" ? "UserGems" : "UserCoins";
        PlayerPrefs.SetInt(key, PlayerPrefs.GetInt(key, 0) + amount);
        PlayerPrefs.Save();
    }

    private void OnDestroy()
    {
        LevelPlay.OnInitSuccess -= OnSdkInitSuccess;

        if (rewardedAd != null)
        {
            rewardedAd.OnAdLoaded -= OnRewardedAdLoaded;
            rewardedAd.OnAdLoadFailed -= OnRewardedAdLoadFailed;
            rewardedAd.OnAdDisplayed -= OnRewardedAdDisplayed;
            rewardedAd.OnAdDisplayFailed -= OnRewardedAdDisplayFailed;
            rewardedAd.OnAdClicked -= OnRewardedAdClicked;
            rewardedAd.OnAdRewarded -= OnRewardedAdRewarded;
            rewardedAd.OnAdClosed -= OnRewardedAdClosed;
            rewardedAd.Dispose();
            rewardedAd = null;
        }
    }
}

Key Production Safeguards in This Controller

  1. Named event handlers + Dispose(): Avoiding anonymous lambdas on LevelPlay.OnInitSuccess guarantees you can cleanly unsubscribe in OnDisable/OnDestroy and prevent memory leaks or duplicate callbacks across scene reloads.
  2. Duplicate reward guard: Checking both rewardGrantedForCurrentShow and adInfo.AuctionId prevents accidental double-crediting if a mediation adapter fires a duplicate callback.
  3. OnAdDisplayFailed recovery: Always reload after a display failure so the placement does not stay stuck in an unready state.
  4. Accurate revenue logging: LevelPlayAdInfo.Revenue represents estimated per-impression revenue in USD, not eCPM (eCPM = Revenue × 1000).

3. Server-to-Server (S2S) Reward Validation (Illustrative Backend Example)

If your game has a server-authoritative economy, configure a Server-to-Server Callback URL in the LevelPlay dashboard:

TEXT
https://api.yourdomain.com/levelplay/reward?userid=[USER_ID]&rewards=[REWARDS]&eventId=[EVENT_ID]&timestamp=[TIMESTAMP]&signature=[SIGNATURE]

Per Unity LevelPlay's S2S documentation, LevelPlay computes the callback signature as:

signature = MD5(timestamp + eventId + decodedUserId + rewards + PRIVATE_KEY)

The following illustrative Node.js / Express handler shows how to validate the signature and enforce eventId idempotency before crediting a player:

JAVASCRIPT
// Illustrative backend snippet — adapt database & timing-safe storage to your stack
const crypto = require('crypto');

app.get('/levelplay/reward', async (req, res) => {
  const { userid, rewards, eventId, timestamp, signature } = req.query;
  const privateKey = process.env.LEVELPLAY_PRIVATE_KEY;

  if (!userid || !rewards || !eventId || !timestamp || !signature || !privateKey) {
    return res.status(400).send('Missing parameters');
  }

  // Reconstruct MD5(timestamp + eventId + decodedUserId + rewards + privateKey)
  const raw = `${timestamp}${eventId}${userid}${rewards}${privateKey}`;
  const expected = crypto.createHash('md5').update(raw).digest('hex');

  const sigBuf = Buffer.from(String(signature), 'utf8');
  const expBuf = Buffer.from(expected, 'utf8');
  if (sigBuf.length !== expBuf.length || !crypto.timingSafeEqual(sigBuf, expBuf)) {
    return res.status(403).send('Invalid signature');
  }

  // Enforce idempotency with a unique DB constraint on eventId
  const alreadyProcessed = await db.hasRewardEvent(eventId);
  if (alreadyProcessed) {
    return res.status(200).send('OK');
  }

  await db.grantRewardAtomically({ userId: userid, amount: Number(rewards), eventId });
  return res.status(200).send('OK');
});

Always verify your endpoint with the Callback Test tool in the LevelPlay dashboard before releasing to production.


4. Configuring Ad Network Mediation in LevelPlay

To increase auction competition, add demand networks in the LevelPlay Dashboard under Setup > SDK Networks and install their matching adapters via the LevelPlay Network Manager (EDM4U).

Common Network Adapters & Prerequisites

Ad Network Demand SourceMediation ModelsSetup Prerequisite
Google AdMobIn-App Bidding & WaterfallConfigure AdMob App ID in LevelPlay / Android & iOS manifests
AppLovinIn-App Bidding & WaterfallAdd AppLovin SDK Key and Zone/Ad Unit IDs in LevelPlay dashboard
Meta Audience NetworkIn-App Bidding OnlyRequires Meta Business Manager verification and Placement IDs
Unity AdsIn-App Bidding & WaterfallLink Unity Organization / Project Game IDs
MintegralIn-App Bidding & WaterfallConfigure App ID, App Key, and Placement/Unit IDs for global & APAC demand

5. Official Documentation References


6. Part 2 Summary & Next Steps

In this installment, we implemented LevelPlayRewardedAd on Unity.Services.LevelPlay v9+, added proper event cleanup and duplicate-reward guards, outlined S2S signature verification, and reviewed mediation adapter prerequisites.

👉 Continue to Part 3: eCPM Optimization, A/B Testing, LiveOps & ARPDAU Maximization →


💡 Looking for a Custom Ad Monetization & LiveOps Strategy?

Struggling with mediation configuration, S2S validation, or ad-driven retention drops? I work directly with mobile game studios to architect maintainable ad mediation, IAP economies, and LiveOps systems:

  • Mediation & Bidding Architecture: Clean LevelPlay v9+ setups across AdMob, AppLovin, Unity Ads, and Meta.
  • Segmented Monetization: Tailored ad rules for non-payers vs. paying players.
  • LiveOps & Retention Tuning: Balancing ad exposure alongside D7/D30 retention and LTV.

👉 Book a Game Monetization & LiveOps Strategy Session or reach out directly to discuss your game's architecture.


🎮 Shipped Mobile Games & Official Store Profiles

Explore live commercial titles built with Unity and published across official app stores:


Planning to monetize your mobile game or optimize your engineering budget? Check out our 2026 Mobile Game Development Cost Guide or book an engineering consultation.

Need help architecting or optimizing your Unity mobile game? Let's discuss your technical roadmap.

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