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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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);
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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.