Unity Ads

Wow. That was easier than I expected. I signed up in the services section of Unity, turned on “test mode”. Then created a button and added the following 2 scripts to said button and it worked like a charm 🙂

This code shows the rewarded ad types. Video ads that the player chooses to watch and will be rewarded if they are seen to the end.

using UnityEngine;
using UnityEngine.Advertisements;

public class UnityAdsInitializer : MonoBehaviour {
    [SerializeField]
    private string
        androidGameId = "Number Found In Services->Settings->Advanced",
        iosGameId = "Number Found In Services->Settings->Advanced";

    [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);
        }
    }
}

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

public class WatchAd : MonoBehaviour {

    [SerializeField]
    private string placementId = null;

    private Button _button;

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

        if (_button) {
            _button.interactable = false;
            _button.onClick.AddListener(ShowAd);
        }
    }

    void Update() {
        if (_button == null) return;

        _button.interactable = (
            Advertisement.isInitialized &&
            Advertisement.IsReady(placementId)
        );
    }

    public void ShowAd() {
        var options = new ShowOptions { resultCallback = HandleShowResult };
        Advertisement.Show(placementId, options);
    }

    private void HandleShowResult(ShowResult result) {
        switch (result) {
            case ShowResult.Finished:
                Debug.Log("The ad was successfully shown.");
                //
                // YOUR CODE TO REWARD THE GAMER
                // Give coins etc.
                break;
            case ShowResult.Skipped:
                Debug.Log("The ad was skipped before reaching the end.");
                break;
            case ShowResult.Failed:
                Debug.LogError("The ad failed to be shown.");
                break;
        }
    }
}

I’m now hoping that in-app purchases will be this simple (although I doubt it).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.