integration guide unity - Unity-Technologies/unity-ads GitHub Wiki

/*
Title: Integration guide for Unity Description: A guide to integrating Unity Ads in Unity (C#)
Sort: 1 */

Overview

This guide covers integration for implementing Unity Ads in your made-with-Unity game.

  • If you are an iOS developer using Objective-C, click here.
  • If you are an Android developer using Java, click here.
  • Click here for the Unity (C#) API reference.

In this guide:

Basic ads implementation

Configuring your project

Setting build targets

Configure your project for a supported platform using the Build Settings window. Set the platform to iOS or Android, then click Switch Platform.

Setting build targets in the Unity Editor

Installing Unity Ads

To ensure the latest version of Unity Ads, Unity recommends installing it from the Unity Package Manager in the Editor.

Important: You must choose either the Asset or the package. Installing both may lead to build errors.

Install the latest version of Unity Ads through the Unity Package Manager, by following these steps:

  1. In the Unity Editor, select Window > Package Manager to open the Package Manager.
  2. Select the Advertisements package from the list, then select the most recent verified version.
  3. Click the Install or Update button.

Creating Ad Units in your game

Ad Units are surfacing points that trigger ads in your game. Create Ad Units in the Monetize Dashboard by selecting your project, then selecting Monetization > Ad Units from the navigation bar.

Click the Add Ad Unit button to bring up the creation modal. Enter your Ad Unit ID and select its type:

  • Select Rewarded video to allow players to opt-in to viewing ads in exchange for incentives. Rewarded Ad Units do not allow the player to skip the ad.
  • Select Interstitial video to show basic interstitial ads or promotional content. Interstitial Ad Units allow players to skip the ad after a specified period of time.
  • Select Banner to create a dedicated Banner Ad Unit.

Every Unity Ads-enabled project has one Ad Unit for each format (rewarded, interstitial, and banner) per platform by default. Feel free to use one of these for your first implementation if they suit your needs, or create your own.

For more information, see documentation on Ad Units.

Initializing the SDK

To initialize the SDK, you must reference your project’s Game ID for the appropriate platform. You can locate the ID in the Monetize Dashboard by selecting Project Settings from the navigation bar (see the Dashboard guide section on Project Settings for details).

In your game script header, include the UnityEngine.Advertisements namespace. Initialize the SDK early in the game’s run-time life cycle, preferably at launch, using the Initialize function.

In SDK versions 3.7.0 and higher, you can use IUnityAdsInitializationListener callbacks to receive a notification when initialization is complete, or receive the details when an error occurs.

using UnityEngine;
using UnityEngine.Advertisements;
 
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener
{
    [SerializeField] string _androidGameId;
    [SerializeField] string _iOsGameId;
    [SerializeField] bool _testMode = true;
    [SerializeField] bool _enablePerPlacementMode = true;
    private string _gameId;
 
    void Awake()
    {
        InitializeAds();
    }
 
    public void InitializeAds()
    {
        _gameId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOsGameId
            : _androidGameId;
        Advertisement.Initialize(_gameId, _testMode, _enablePerPlacementMode, this);
    }
 
    public void OnInitializationComplete()
    {
        Debug.Log("Unity Ads initialization complete.");
    }
 
    public void OnInitializationFailed(UnityAdsInitializationError error, string message)
    {
        Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
    }
}

Interstitial display ads

To display a full-screen interstitial ad using the Advertisements API, initialize the SDK, then use the Load function to load ad content to an Ad Unit and the Show function to show the ad.

In SDK versions 3.7.0 and higher, you can use the IUnityAdsLoadListener and IUnityAdsShowListener callbacks to implement logic for when content succeeds or fails to load or show respectively.

using UnityEngine;
using UnityEngine.Advertisements;
 
public class InterstitialAdExample : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] string _androidAdUnitId = "Interstitial_Android";
    [SerializeField] string _iOsAdUnitId = "Interstitial_iOS";
    string _adUnitId;
 
    void Awake()
    {
        // Get the Ad Unit ID for the current platform:
        _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOsAdUnitId
            : _androidAdUnitId;
    }
 
    // Load content to the Ad Unit:
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + _adUnitId);
        Advertisement.Load(_adUnitId, this);
    }
 
    // Show the loaded content in the Ad Unit: 
    public void ShowAd()
    {
        // Note that if the ad content wasn't previously loaded, this method will fail
        Debug.Log("Showing Ad: " + _adUnitId);
        Advertisement.Show(_adUnitId, this);
    }
  
    // Implement Load Listener and Show Listener interface methods:  
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        // Optionally execute code if the Ad Unit successfully loads content.
    }
 
    public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit: {adUnitId} - {error.ToString()} - {message}");
        // Optionally execite code if the Ad Unit fails to load, such as attempting to try again.
    }
 
    public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Optionally execite code if the Ad Unit fails to show, such as loading another ad.
    }
 
    public void OnUnityAdsShowStart(string adUnitId) { }
    public void OnUnityAdsShowClick(string adUnitId) { }
    public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState) { }
}

Note: If you call Show() without specifying an Ad Unit ID, the method shows loaded content in the Unity Standard Placement.

Rewarded video ads

Rewarding players for watching ads increases user engagement, resulting in higher revenue. For example, games may reward players with in-game currency, consumables, additional lives, or experience-multipliers. For more information on how to effectively design your rewarded ads, see documentation on Ads best practices.

To reward players for completing a video ad, implement a callback method using the ShowResult result to check if the user finished the ad and should be rewarded.

Rewarded ad buttons

Using a button that prompts the player to opt in to watching an ad is a common implementation for rewarded video ads. Use the example code below to create a rewarded ads button. The button displays an ad when pressed, as long as ad content is available. To configure a button in the Unity Editor:

  1. Select Game Object > UI > Button to add a button to your Scene.
  2. Select the button you added to your Scene, then add a script component to it using the Inspector (Add Component > New Script). Name the script RewardedAdsButton to match the class name.
  3. Open the script and add the following code:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
 
public class RewardedAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] Button _showAdButton;
    [SerializeField] string _androidAdUnitId = "Rewarded_Android";
    [SerializeField] string _iOsAdUnitId = "Rewarded_iOS";
    string _adUnitId;
 
    void Awake()
    {
        // Get the Ad Unit ID for the current platform:
        _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOsAdUnitId
            : _androidAdUnitId;
 
        //Disable button until ad is ready to show
        _showAdButton.interactable = false;
    }
 
    // Load content to the Ad Unit:
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + _adUnitId);
        Advertisement.Load(_adUnitId, this);
    }
 
    // If the ad successfully loads, add a listener to the button and enable it:
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        Debug.Log("Ad Loaded: " + adUnitId);
 
        if (adUnitId.Equals(_adUnitId))
        {
            // Configure the button to call the ShowAd() method when clicked:
            _showAdButton.onClick.AddListener(ShowAd);
            // Enable the button for users to click:
            _showAdButton.interactable = true;
        }
    }
 
    // Implement a method to execute when the user clicks the button.
    public void ShowAd()
    {
        // Disable the button: 
        _showAdButton.interactable = false;
        // Then show the ad:
        Advertisement.Show(_adUnitId, this);
    }
 
    // Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
    public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
    {
        if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
        {
            Debug.Log("Unity Ads Rewarded Ad Completed");
            // Grant a reward.
 
            // Load another ad:
            Advertisement.Load(_adUnitId, this);
        }
    }
 
    // Implement Load and Show Listener error callbacks:
    public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Use the error details to determine whether to try to load another ad.
    }

    public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Use the error details to determine whether to try to load another ad.
    }
 
    public void OnUnityAdsShowStart(string adUnitId) { }
    public void OnUnityAdsShowClick(string adUnitId) { }
 
    void OnDestroy()
    {
        // Clean up the button listeners:
        _showAdButton.onClick.RemoveAllListeners();
    }
}

Banner ads

Banner ads require a specific type of dedicated Banner Ad Unit.

Example of a banner ad in-game

Important: app-ads.txt is an IAB initiative to combat fraud and create transparency in the advertising ecosystem. Be sure to implement app-ads.txt as described. Otherwise, banner demand may significantly decrease.

Script implementation

In your script header, declare the UnityEngine.Advertisements namespace, which contains the Banner class. Next, initialize the SDK, then use Banner.Load and Banner.Show to load and display a banner ad.

The following example script shows you how to set up buttons in a Scene to test this functionality. To create a button in the Unity Editor, select Game Object > UI > Button.

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
 
public class BannerAdExample : MonoBehaviour
{
    // For the purpose of this example, these buttons are for functionality testing:
    [SerializeField] Button _loadBannerButton;
    [SerializeField] Button _showBannerButton;
    [SerializeField] Button _hideBannerButton;

    [SerializeField] BannerPosition _bannerPosition = BannerPosition.BOTTOM_CENTER;
 
    [SerializeField] string _androidAdUnitId = "Banner_Android";
    [SerializeField] string _iOsAdUnitId = "Banner_iOS";
    string _adUnitId;
 
    void Start()
    {
        // Disable the button until an ad is ready to show:
        _showBannerButton.interactable = false;
        _hideBannerButton.interactable = false;
 
        // Set the banner position:
        Advertisement.Banner.SetPosition(_bannerPosition);
 
        // Configure the Load Banner button to call the LoadBanner() method when clicked:
        _loadBannerButton.onClick.AddListener(LoadBanner);
        _loadBannerButton.interactable = true;
    }
 
    // Implement a method to call when the Load Banner button is clicked:
    public void LoadBanner()
    {
        // Set up options to notify the SDK of load events:
        BannerLoadOptions options = new BannerLoadOptions
        {
            loadCallback = OnBannerLoaded,
            errorCallback = OnBannerError
        };
 
        // Load the Ad Unit with banner content:
        Advertisement.Banner.Load(_adUnitId, options);
    }
 
    // Implement code to execute when the loadCallback event triggers:
    void OnBannerLoaded()
    {
        Debug.Log("Banner loaded");
        
        // Configure the Show Banner button to call the ShowBannerAd() method when clicked:
        _showBannerButton.onClick.AddListener(ShowBannerAd);
        // Configure the Hide Banner button to call the HideBannerAd() method when clicked:
        _hideBannerButton.onClick.AddListener(HideBannerAd);

        // Enable both buttons:
        _showBannerButton.interactable = true;
        _hideBannerButton.interactable = true;      
    }

    // Implement code to execute when the load errorCallback event triggers:
    void OnBannerError(string message)
    {
        Debug.Log($"Banner Error: {message}");
        // Optionally execute additional code, such as attempting to load another ad.
    }
 
    // Implement a method to call when the Show Banner button is clicked:
    void ShowBannerAd()
    {
        // Set up options to notify the SDK of show events:
        BannerOptions options = new BannerOptions
        {
            clickCallback = OnBannerClicked,
            hideCallback = OnBannerHidden,
            showCallback = OnBannerShown
        };
        
        // Show the loaded Banner Ad Unit:
        Advertisement.Banner.Show(_adUnitId, options);
    }
 
    // Implement a method to call when the Hide Banner button is clicked:
    void HideBannerAd()
    {
        // Hide the banner:
        Advertisement.Banner.Hide();
    }
 
    void OnBannerClicked() { }
    void OnBannerShown() { }
    void OnBannerHidden() { }
 
    void OnDestroy()
    {
        // Clean up the listeners:
        _loadBannerButton.onClick.RemoveAllListeners();
        _showBannerButton.onClick.RemoveAllListeners();
        _hideBannerButton.onClick.RemoveAllListeners();
    }
}

Banner position

By default, banner ads display anchored on the bottom-center of the screen, supporting 320 x 50 or 728 x 90 pixel resolution. To specify the banner achor, use the Banner.SetPosition API. For example:

Advertisement.Banner.SetPosition (BannerPosition.TOP_CENTER);

Testing

Prior to publishing your game, enable test mode by following these steps:

  1. From the Monetize Dashboard, select your project.
  2. Select project Settings from the navigation bar.
  3. Scroll down to the Test mode section.
  4. Edit either the Apple App Store or Google Play Store depending on which device you want to enable the test mode.
  5. Select the Override client test mode checkbox, then select the Force test mode ON for all devices radio button.

In the Unity Editor, click the Play button to run your project and test your ads implementation.

Important: You must enable test mode before testing ads integration, to avoid getting flagged for fraud.

⚠️ **GitHub.com Fallback** ⚠️