Knowledge base

Integration guide for Unity

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, download it through the Asset store, or through the Unity Package Manager in the Editor.

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

Using the Asset package

Download the latest version of Unity Ads from the Asset store. For information on downloading and installing Asset packages, see Asset packages documentation.

Using Package Manager

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 surfacing points in your game

A surfacing point is an event in your game that will trigger ad content. These are represented by legacy Placements or Ad Units. During Unity’s phased rollout of Ad Units, certain customers will use the legacy Placement system, while some customers will use the new Ad Units system. For more information about which applies to you, see documentation on the Ad Units transitional period.

Creating legacy Placements

Create and manage Placements from the Monetize Dashboard by selecting your Project, then selecting Monetization > Placements from the navigation bar.

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

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

Every Unity Ads-enabled project has a (non-rewarded) ‘video’ and (rewarded) ‘rewardedVideo’ Placement by default. Feel free to use one of these for your first implementation if they suit your needs, or create your own.

Creating Ad Units

Create and manage Ad Units from 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 Placements 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. For example:

using UnityEngine;
using UnityEngine.Advertisements;

public class InitializeAdsScript : MonoBehaviour { 

    string gameId = "1234567";
    bool testMode = true;

    void Start () {
        Advertisement.Initialize (gameId, testMode);
    }
}

Interstitial display ads

To display a full-screen interstitial ad using the Advertisements API, simply initialize the SDK and use the Show function.

Interstitial example

using UnityEngine;
using UnityEngine.Advertisements;

public class InterstitialAdsScript : MonoBehaviour { 

    string gameId = "1234567";
    bool testMode = true;

    void Start () {
        // Initialize the Ads service:
        Advertisement.Initialize(gameId, testMode);
    }

    public void ShowInterstitialAd() {
        // Check if UnityAds ready before calling Show method:
        if (Advertisement.IsReady()) {
            Advertisement.Show();
        } 
        else {
            Debug.Log("Interstitial ad not ready at the moment! Please try again later!");
        }
    }
}

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.

Important: Rewarded ads require you to pass a surfacing point ID into the Show method and result callback methods. Customers using Ad Units and Unity as their exclusive ads provider must use Ad Unit IDs. All other customers must use Placement IDs.

Ad Units or legacy Placements Ads provider Surfacing point ID
Ad Units Unity exclusive Ad Unit ID
Ad Units 3rd-party mediated Placement ID
Legacy Placements Unity exclusive Placement ID
Legacy Placements 3rd-party mediated Placement ID

Rewarded video example

using UnityEngine;
using UnityEngine.Advertisements;

public class RewardedAdsScript : MonoBehaviour, IUnityAdsListener { 

    string gameId = "1234567";
    string mySurfacingId = "rewardedVideo";
    bool testMode = true;

    // Initialize the Ads listener and service:
    void Start () {
        Advertisement.AddListener (this);
        Advertisement.Initialize (gameId, testMode);
    }

    public void ShowRewardedVideo() {
        // Check if UnityAds ready before calling Show method:
        if (Advertisement.IsReady(mySurfacingId)) {
            Advertisement.Show(mySurfacingId);
        } 
        else {
            Debug.Log("Rewarded video is not ready at the moment! Please try again later!");
        }
    }

    // Implement IUnityAdsListener interface methods:
    public void OnUnityAdsDidFinish (string surfacingId, ShowResult showResult) {
        // Define conditional logic for each ad completion status:
        if (showResult == ShowResult.Finished) {
            // Reward the user for watching the ad to completion.
        } else if (showResult == ShowResult.Skipped) {
            // Do not reward the user for skipping the ad.
        } else if (showResult == ShowResult.Failed) {
            Debug.LogWarning ("The ad did not finish due to an error.");
        }
    }

    public void OnUnityAdsReady (string surfacingId) {
        // If the ready Ad Unit or legacy Placement is rewarded, show the ad:
        if (surfacingId == mySurfacingId) {
            // Optional actions to take when theAd Unit or legacy Placement becomes ready (for example, enable the rewarded ads button)
        }
    }

    public void OnUnityAdsDidError (string message) {
        // Log the error.
    }

    public void OnUnityAdsDidStart (string surfacingId) {
        // Optional actions to take when the end-users triggers an ad.
    } 

    // When the object that subscribes to ad events is destroyed, remove the listener:
    public void OnDestroy() {
        Advertisement.RemoveListener(this);
    }
}

Rewarded video ad buttons

Using a button to allow 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 ads button displays an ad when pressed, as long as ads are available. To configure the 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;

[RequireComponent (typeof (Button))]
public class RewardedAdsButton : MonoBehaviour, IUnityAdsListener {

    #if UNITY_IOS
    private string gameId = "1486551";
    #elif UNITY_ANDROID
    private string gameId = "1486550";
    #endif

    Button myButton;
    public string mySurfacingId = "rewardedVideo";

    void Start () {   
        myButton = GetComponent <Button> ();

        // Set interactivity to be dependent on the Ad Unit or legacy Placement’s status:
        myButton.interactable = Advertisement.IsReady (mySurfacingId); 

        // Map the ShowRewardedVideo function to the button’s click listener:
        if (myButton) myButton.onClick.AddListener (ShowRewardedVideo);

        // Initialize the Ads listener and service:
        Advertisement.AddListener (this);
        Advertisement.Initialize (gameId, true);
    }

    // Implement a function for showing a rewarded video ad:
    void ShowRewardedVideo () {
        Advertisement.Show (mySurfacingId);
    }

    // Implement IUnityAdsListener interface methods:
    public void OnUnityAdsReady (string surfacingId) {
        // If the ready Ad Unit or legacy Placement is rewarded, activate the button: 
        if (surfacingId == mySurfacingId) {        
            myButton.interactable = true;
        }
    }

    public void OnUnityAdsDidFinish (string surfacingId, ShowResult showResult) {
        // Define conditional logic for each ad completion status:
        if (showResult == ShowResult.Finished) {
            // Reward the user for watching the ad to completion.
        } else if (showResult == ShowResult.Skipped) {
            // Do not reward the user for skipping the ad.
        } else if (showResult == ShowResult.Failed) {
            Debug.LogWarning (“The ad did not finish due to an error.”);
        }
    }

    public void OnUnityAdsDidError (string message) {
        // Log the error.
    }

    public void OnUnityAdsDidStart (string surfacingId) {
        // Optional actions to take when the end-users triggers an ad.
    } 
}

Banner ads require a specific type of dedicated banner Ad Unit or legacy Placement.

Example of a banner ad in-game

Script implementation

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

app-ads.txt

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 be significantly decreased.

using System.Collections;
using UnityEngine;
using UnityEngine.Advertisements;

public class BannerAdScript : MonoBehaviour {

    public string gameId = "1234567";
    public string surfacingId = "bannerPlacement";
    public bool testMode = true;

    void Start () {
        Advertisement.Initialize(gameId, testMode);
        StartCoroutine(ShowBannerWhenInitialized());
    }

    IEnumerator ShowBannerWhenInitialized () {
        while (!Advertisement.isInitialized) {
            yield return new WaitForSeconds(0.5f);
        }
        Advertisement.Banner.Show (surfacingId);
    }
}

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.

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

Still need help? Get in touch!
Last updated on 12th Apr 2021