How do I implement admob rewarded ads into unity

Physix picture Physix · May 16, 2016 · Viewed 9.1k times · Source
using UnityEngine;
using System.Collections;
using GoogleMobileAds;
using GoogleMobileAds.Api;
using UnityEngine.Advertisements;

public class GameAdvertising : MonoBehaviour {

    public RewardBasedVideoAd rewardBasedVideo;
    bool hasPlayed;

    void Start () {
        rewardBasedVideo = RewardBasedVideoAd.Instance;
    }

    public void playAd()
    {
        AdRequest rewardrequest = new AdRequest.Builder().Build(); 
        rewardBasedVideo.LoadAd(rewardrequest, "ca-app-pub-5920324855307233/4458481507");
        rewardBasedVideo.Show();
    }
}

In my code above I have tried to implement the admob reward video ad into my game inside a method that is called from a ui button press. The advertise did not appear on my phone when the method was called (It works on the demo script and banners etc. works. I have imported all SDks and other files successful). What did I do wrong here and how do i put it in properly. Also how do i check when the ad is finished so i can reward the user?

Answer

Programmer picture Programmer · May 17, 2016

You need to subscribe to OnAdRewarded Ad event with RewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;.

Just call RequestRewardBasedVideo() from the Start function to test this. This code below is from here and I modified it a little bit.

private void RequestRewardBasedVideo()
{
    #if UNITY_EDITOR
        string adUnitId = "unused";
    #elif UNITY_ANDROID
        string adUnitId = "INSERT_AD_UNIT_HERE";
    #elif UNITY_IPHONE
        string adUnitId = "INSERT_AD_UNIT_HERE";
    #else
        string adUnitId = "unexpected_platform";
    #endif

    RewardBasedVideoAd rewardBasedVideo = RewardBasedVideoAd.Instance;

    AdRequest request = new AdRequest.Builder().Build();
    rewardBasedVideo.LoadAd(request, adUnitId);

    //Show Ad
    showAdd(rewardBasedVideo);
}

private void showAdd(RewardBasedVideoAd rewardBasedVideo)
{
    if (rewardBasedVideo.IsLoaded())
    {
        //Subscribe to Ad event
        rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
        rewardBasedVideo.Show();
    }
}

//This function is called when video ad has finished showing You can reward player here with the amount variable.

public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
    string type = args.Type;
    double amount = args.Amount;
    //Reawrd User here
    print("User rewarded with: " + amount.ToString() + " " + type);
}