Knowledge base

Integration Guide for Unity

Outline

Quick Start

Before going into too much detail, let's start off with a simple integration example. Every Unity Ads integration boils down to just 3 basic steps:

  1. Setup and initialization.
  2. Verify ads are ready.
  3. Show an ad.

The following example initializes Unity Ads on Start, and shows the default ad placement when ready. If the Ads service is enabled in the Services window, Unity will initialize Unity Ads for you instead. The rest of the example is the same, regardless of whether you are using the Services window or the Unity Ads asset package.

C# Example – ShowAdOnStart.cs

using UnityEngine;
using System.Collections;
using UnityEngine.Advertisements; // Using the Unity Ads namespace.

public class ShowAdOnStart : MonoBehaviour
{
    #if !UNITY_ADS // If the Ads service is not enabled...
    public string gameId; // Set this value from the inspector.
    public bool enableTestMode = true;
    #endif

    IEnumerator Start ()
    {
        #if !UNITY_ADS // If the Ads service is not enabled...
        if (Advertisement.isSupported) { // If runtime platform is supported...
            Advertisement.Initialize(gameId, enableTestMode); // ...initialize.
        }
        #endif

        // Wait until Unity Ads is initialized,
        //  and the default ad placement is ready.
        while (!Advertisement.isInitialized || !Advertisement.IsReady()) {
            yield return new WaitForSeconds(0.5f);
        }

        // Show the default ad placement.
        Advertisement.Show();
    }
}

JavaScript Example – ShowAdOnStart.js

#pragma strict
import UnityEngine.Advertisements; // Import the Unity Ads namespace.

#if !UNITY_ADS // If the Ads service is not enabled...
public var gameId : String; // Set this value from the inspector.
public var enableTestMode : boolean = true;
#endif

function Start () : IEnumerator
{
    #if !UNITY_ADS // If the Ads service is not enabled...
    if (Advertisement.isSupported) { // If runtime platform is supported...
        Advertisement.Initialize(gameId, enableTestMode); // ...initialize.
    }
    #endif

    // Wait until Unity Ads is initialized,
    //  and the default ad placement is ready.
    while (!Advertisement.isInitialized || !Advertisement.IsReady()) {
        yield WaitForSeconds(0.5);
    }

    // Show the default ad placement.
    Advertisement.Show();
}

Now let's take a closer look at the Unity Ads integration.

Setup and Initialization

There are two options available for integrating Unity Ads in Unity:

As of Unity 5.2, the Unity Ads API is now included as part of the Unity engine. One of the benefits of having Unity Ads in-engine is that it significantly simplifies the setup and initialization process, getting you up and running faster.

However, if you decide not to use the Services window, you still have the option of using the Unity Ads asset package in Unity 5.2 and later. The Unity Ads asset package is compatible with Unity 4.3 and later.

⇧ Back to top

Using the Services Window

This section covers how to setup and enable Unity Ads using the Services window in Unity 5.2 and later.

Note: When enabled through the Services window, the in-engine version of Unity Ads will conflict with any assets that have been imported from the Unity Ads asset package.

If you already have Unity Ads integrated in your project using the Unity Ads asset package, and are upgrading to Unity 5.2 or later, or planning to use Unity Ads through the Services window, you will need to delete any assets that were previously imported from the Unity Ads asset package.

These assets can be found in the following locations:

  • Plugins/Android/unityads
  • Plugins/iOS/UnityAds.bundle
  • Plugins/iOS/UnityAds.framework
  • Plugins/iOS/UnityAdsUnityWrapper.h
  • Plugins/iOS/UnityAdsUnityWrapper.mm
  • StandardAssets/Editor/UnityAds
  • StandardAssets/UnityAds

One easy solution is to use the Package Uninstaller, available for free through the Asset Store.

To get started with your Unity Ads integration, follow these steps to setup and enable Unity Ads using the Services window.

Step 1: Set the Platform to either iOS or Android.

  1. Select File > Build Settings... from the Unity menu.
  2. Select iOS or Android from the Platform list.
  3. Select Switch Platform.

Step 2: Enable Unity Ads through the Services window.

  1. Select Window > Services to open the Services window.
  2. Select the Ads service to configure settings.
  3. Select the toggle switch to enable Ads (upper-right of Ads in the Services window).
  4. Indicate whether your game is designed specifically for children under the age of 13, or not.
  5. Select Save Changes to finish the setup.

When you indicate whether your game is designed for children under the age of 13, ads will not be behaviorally targeted to users in your game. Behavioral targeting can yield higher eCPMs by showing ads that are more relevant to users, but its use is prohibited with users under the age of 13 due to COPPA regulations.

With Ads enabled through the Services window, Unity Ads will automatically be initialized when the game starts. You can view the game IDs used to initialize Unity Ads under the Advanced section of Ads in the Services window.

For more details, see the Unity Ads section of the Unity Manual. To continue with the integration, skip ahead to Showing an Ad Placement. Also, be sure to review the section on Using Test Mode.

Need to disable auto initialization on startup?

If your application design demands more control over when Unity Ads is initialized, you can disable automatic initialization using an editor script.

Please keep in mind though, you should initialize Unity Ads early enough in your game to allow the first video ad to be cached. Providing a minute or two under good network conditions should be sufficient time to initialize Unity Ads and cache the first ad. Also, if you are initializing more than one third-party SDK at the same time, you may need to allow for more time under the additional overhead and shared bandwidth.

To disable the initialization of Unity Ads on startup, create a new C# script called UnityAdsBuildProcessor, and place it within the Editor folder in your project. Then copy the following code into the script:

using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.Advertisements;

public class UnityAdsBuildProcessor : Editor
{
    [PostProcessScene]
    public static void OnPostprocessScene ()
    {
        AdvertisementSettings.enabled = true;
        AdvertisementSettings.initializeOnStartup = false;
    }
}

This script will execute just prior to playing the game in editor, and before generating builds. With this script, Unity Ads will be enabled and available to use, but will not automatically be initialized when the game starts.

To manually initialize Unity Ads, follow Step 3 through Step 6 under the following section for Using the Asset Package.

⇧ Back to top

Using the Asset Package

This section covers how to setup and initialize Unity Ads using the Unity Ads asset package in Unity 4.3 and later.

Note: If you are using Unity 5.2 or later, you can still use the Unity Ads asset package for Unity Ads integrations. However, we do strongly recommend using the in-engine version of Unity Ads by enabling Unity Ads through the Services window instead.

Unity Ads must remain disabled in the Services window if you choose to continue using the Unity Ads asset package in Unity 5.2 or later.

To get started with your Unity Ads integration, follow these steps to setup and initialize Unity Ads using the Unity Ads asset package.

Step 1: Set the Platform to either iOS or Android.

  1. Select File > Build Settings... from the Unity menu.
  2. Select iOS or Android from the Platform list.
  3. Select Switch Platform.

Step 2: Download and import the Unity Ads asset package.

Step 3: Create a new GameObject called UnityAdsExample.

  1. Select GameObject > Create Empty from the Unity menu.
  2. Locate the new GameObject in the Hierarchy window.
  3. Right-click on the GameObject and select Rename.
  4. Enter UnityAdsExample and press the return key.

Step 4: Create a new C# script called UnityAdsExample.

  1. Select Assets > Create > C# Script from the Unity menu.
  2. Enter UnityAdsExample as the name and press the return key.
  3. Right-click the script and select Open to begin editing it.
  4. Copy the following example code into the script:

C# Example – UnityAdsExample.cs

using UnityEngine;
using UnityEngine.Advertisements;

public class UnityAdsInitializer : MonoBehaviour
{
    [SerializeField]
    private string
        androidGameId = "18658",
        iosGameId = "18660";

    [SerializeField]
    private bool testMode;

    void Start ()
    {
        string gameId = null;

        #if UNITY_ANDROID
        gameId = androidGameId;
        #elif UNITY_IOS
        gameId = iosGameId;
        #endif

        if (Advertisement.isSupported && !Advertisement.isInitialized) {
            Advertisement.Initialize(gameId, testMode);
        }
    }
}

Step 5: Add the script to the UnityAdsExample GameObject.

  1. Select the UnityAdsExample GameObject in the Hierarchy window.
  2. Select Component > Scripts > Unity Ads Example from the Unity menu.

Step 6: With the GameObject selected, set the Game ID field in the Inspector window.

If you don't know what your Game ID is, you can find it in the list of platforms for your project in the Unity Ads dashboard.

If you are still using the old Unity Ads admin, you can find your Game IDs listed under the Games section of the admin.

Improving the UnityAdsExample

Let's expand on the initial example by adding support for the following:

  • Game ID fields for both iOS and Android.
  • An option to enable Test Mode for Unity Ads.

C# Example – UnityAdsExample.cs

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

public class UnityAdsExample : MonoBehaviour
{

  [SerializeField] private string androidGameId = "18658"; //ID for testing
  [SerializeField] private string iosGameId = "18660"; //ID for testing

    [SerializeField] bool enableTestMode;

    void Start ()
    {
        string gameId = null;

        #if UNITY_IOS // If build platform is set to iOS...
        gameId = iosGameId;
        #elif UNITY_ANDROID // Else if build platform is set to Android...
        gameId = androidGameId;
        #endif

        if (string.IsNullOrEmpty(gameId)) { // Make sure the Game ID is set.
            Debug.LogError("Failed to initialize Unity Ads. Game ID is null or empty.");
        } else if (!Advertisement.isSupported) {
            Debug.LogWarning("Unable to initialize Unity Ads. Platform not supported.");
        } else if (Advertisement.isInitialized) {
            Debug.Log("Unity Ads is already initialized.");
        } else {
            Debug.Log(string.Format("Initialize Unity Ads using Game ID {0} with Test Mode {1}.",
                gameId, enableTestMode ? "enabled" : "disabled"));
            Advertisement.Initialize(gameId, enableTestMode);
        }
    }
}

⇧ Back to top

Using Test Mode

We strongly recommend enabling Test Mode for Unity Ads during development. While this option is enabled, only test ads will be shown in game. Test ads are not limited to the standard limit of 25 ads per day, and will not affect stats or accidentally generate revenue when clicked on, which is ideal for testing.

Please be aware that you are prohibited under the Unity Ads Terms of Service agreement from generating impressions or installs by clicking on ads within your own game. Doing so will put you at risk of being banned from the Unity Ads network for attempted fraud. As a precaution, it is best to leave Test Mode enabled during development and while testing Unity Ads.

If you are using the Services window in Unity 5.2 or later, Test Mode for Unity Ads will be disabled by default. You can enable or disable this option under Settings for Ads in the Services window.

If you are initializing Unity Ads using the Advertisement.Initialize method instead, Test Mode can be set by passing a boolean value as the second parameter to the method. Please see the Scripting API for further details.

When you get ready to publish your game, Test Ads should be disabled. You can either disable it in Unity before creating your submission build, or you can disable it from the Unity Ads dashboard under under the Settings tab of each platform in your project.

If you are still using the old Unity Ads admin, the Test Mode settings can be found under the Monetization Settings tab of your game profile.

⇧ Back to top

Showing an Ad Placement

This section covers how to simply show an ad placement.

Create a new C# script called UnityAdsButton, and add it to a new GameObject in your scene. Then copy the following code into the script:

C# Example – UnityAdsButton.cs

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

public class UnityAdsButton : MonoBehaviour
{
    void OnGUI ()
    {
        Rect buttonRect = new Rect (10, 10, 150, 50);
        string buttonText = Advertisement.IsReady () ? "Show Ad" : "Waiting...";

        if (GUI.Button (buttonRect, buttonText)) {
            Advertisement.Show ();
        }
    }
}

⇧ Back to top

Showing a Rewarded Ad Placement

This section covers how to show a rewarded ad placement, and handle the show result.

Create a new C# script called UnityAdsRewardedButton, and add it to a new GameObject in your scene. Then copy the following code into the script:

C# Example – UnityAdsRewardedButton.cs

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

public class UnityAdsRewardedButton : MonoBehaviour
{
    public string zoneId;
    public int rewardQty = 250;

    void OnGUI ()
    {
        if (string.IsNullOrEmpty (zoneId)) zoneId = null;

        Rect buttonRect = new Rect (10, 10, 150, 50);
        string buttonText = Advertisement.IsReady (zoneId) ? "Show Ad" : "Waiting...";

        ShowOptions options = new ShowOptions();
        options.resultCallback = HandleShowResult;

        if (GUI.Button (buttonRect, buttonText)) {
            Advertisement.Show (zoneId, options);
        }
    }

    private void HandleShowResult (ShowResult result)
    {
        switch (result)
        {
        case ShowResult.Finished:
            Debug.Log ("Video completed. User rewarded " + rewardQty + " credits.");
            break;
        case ShowResult.Skipped:
            Debug.LogWarning ("Video was skipped.");
            break;
        case ShowResult.Failed:
            Debug.LogError ("Video failed to show.");
            break;
        }
    }
}

⇧ Back to top

Using Server-to-Server Redeem Callbacks

See the Server-to-Server Redeem Callbacks page for more details.

⇧ Back to top

Scripting API Reference

See the Unity Scripting API for Unity Ads:

See the following class to edit the Services window settings for Unity Ads:

⇧ Back to top

Additional Resources

See the Resources page for demos, downloads, support, and more.

⇧ Back to top

Still need help? Get in touch!
Last updated on 24th Feb 2017