Actually play ad and give reward

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.



Unity Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store