Actually play ad and give reward

Hal Brooks
3 min readNov 14, 2021

--

Objective: Provide the player a reward for actually watching a Unity ad.

Rewarded Unity ad where player awarded 100 gems for watching video.

First we need to initialize the ad by creating an AdInitializer script and adding this to AdsManager game object. Three variables are assigned in the inspector, shown below. The Game Id is unique to the game, but not shown here.

AdsManager components

This script uses the IUnityAdsInitializationListener interface requires OnInitializationComplete and OnIntializationFailed. In void Awake a reference to the AdsManager script is assigned to _adsManager variable. The method InitializeAds is then called for this game. When initialization is complete the LoadAd() method on _adManager script is called, discussed later in the article.

Ads Initializer script.

The AdsManager script, shwn below, is completely rewritten to utilize IUnityAdsLoadListener and IUnityAdsShowListener interfaces. The _adUnitID is assigned in the inspector as shown above. The Player script reference is stored in _player and the _shopButton.interactable set to false on Awake so that the button only works when the ad is loaded. The LoadAd() method is called after initialization to load the ad.

Excerpt from ads Manager script showing LoadAd() method.

IUnityAdsLoadListener requires the methods OnUnityAdsAdLoaded and OnUnityAdsFailedToLoad. The former is used AddListener for the ShowAd() method to make the button interactable only if the ad loads. The OnUnityAdsFailedToLoad helps with debugging if the ad fails to load.

Required methods for IUnityAdsLoadListener.

The ShowAds() method disables the button after it is pressed and shows the ad.

ShowAd method on AdsManager.

IUnityAdsShowListener requires four methods: OnUnityAdsShowFailure, OnUnityAdsShowStart, OnUnityAdsShowClick and OnUnityAdsShowComplete. This latter method ensures that the player has watched the video before rewarding the 100 gems by call the GetDiamond script on _player.

Required methods for IUnityAdsShowListener.

The IEnumerator Reload() is used to prevent the player from immediately hitting the button for more gold. After 20 seconds the a new ad is loaded.

--

--

No responses yet