Services: Integrating Unity Ads

Checked with version: 5

-

Difficulty: Beginner

Join us as we explore Unity Ads and how easy it can be to monetize your game projects in Unity. We'll be approaching this from a developer's perspective, so the focus will be on the technical requirements and scripting required to integrate ads and less on the design principles of ad strategies. Let's start making some money. Tutor: Mike Geig

Services: Integrating Unity Ads

Beginner Production

SimpleAds

Code snippet

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

public class SimpleAds : MonoBehaviour 
{
    void Start () 
    {
        Advertisement.Initialize ("33675", true);

        StartCoroutine (ShowAdWhenReady());
    }

    IEnumerator ShowAdWhenReady()
    {
        while (!Advertisement.isReady())
            yield return null;

        Advertisement.Show ();
    }
}

AdManager

Code snippet

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

public class AdManager : MonoBehaviour 
{
    [SerializeField] string gameID = "33675";

    void Awake()
    {
        Advertisement.Initialize (gameID, true);
    }

    public void ShowAd(string zone = "")
    {
        #if UNITY_EDITOR
            StartCoroutine(WaitForAd ());
        #endif

        if (string.Equals (zone, ""))
            zone = null;

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

        if (Advertisement.isReady (zone))
            Advertisement.Show (zone, options);
    }

    void AdCallbackhandler (ShowResult result)
    {
        switch(result)
        {
        case ShowResult.Finished:
            Debug.Log ("Ad Finished. Rewarding player...");
            break;
        case ShowResult.Skipped:
            Debug.Log ("Ad skipped. Son, I am dissapointed in you");
            break;
        case ShowResult.Failed:
            Debug.Log("I swear this has never happened to me before");
            break;
        }
    }

    IEnumerator WaitForAd()
    {
        float currentTimeScale = Time.timeScale;
        Time.timeScale = 0f;
        yield return null;

        while (Advertisement.isShowing)
            yield return null;

        Time.timeScale = currentTimeScale;
    }
}

Related documentation