Actually play ad and give reward
Objective: Provide the player a reward for actually watching a Unity ad.
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.
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.
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.
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.
The ShowAds() method disables the button after it is pressed and shows the ad.
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.
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.