Published on: 14 September, 2017

How to display interstitial ad in Unity after a number of scenes play or a period of 10 minutes play time

Posted by andy | 223 views 0 likes 1 favourites 0 comments
Tumblr Digg Google Plus
How to display interstitial ad in Unity after a number of scenes play or a period of 10 minutes play time.

After creating my first game using Unity. I decided to place an interstitial ad to generate some revenue. I use interstitial ad rather than a normal banner ad because I want to utilize full screen of game play and load the ad after a number of scenes play or for a period of 10 minutes play.

To display an interstitial ad is quite simple. Either you choose with Google Admob or Unity Ad would be fairly easy. I will include both samples for each of the ad, so you can place them on your game app.

First thing you have to do is to Import Google Admob plugin or Unity Ads plugin. For Google Admob plugin, please download the files in here.

https://developers.google.com/admob/unity/start

For Unity ads, you can download the plugin in Unity store. If the link below does not work, you can simply search Unity Ads plugin in google.

https://www.assetstore.unity3d.com/en/#!/content/66123

Once you have decided which plugin you want to use, and you have setup the ad in your Google Admob account or unity ad account, you can start adding Ad banner script as below. I use C# code, so you will need Visual Studio installed on your computer.

Firstly, we will need to create a static AdInitiator.cs script, which will be used to check if it is time to load the ad. In your Unity Project create a new script called AdInitiator.cs, this will be automatically opened in Visual Studio when you click the script file.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace Assets.Scripts
{
	public static class AdInitiator
    {
		public static int sceneCounter = 0;
		public static float lastActiveAdTime = 0f;
		public static float showAdAfterPassTime = 600f;
		public static float showAdAfterPassScenes = 10;
	}
	
	public static void ChangeScene(string sceneName)
    {
        AdInitiator.sceneCounter += 1;
        SceneManager.LoadScene(sceneName);
    }
}

As you can see we create 4 static global variables. sceneCounter variable will be used to record a number of scene play. While the lastActiveAdTime will be used when the first time the ad has been initially load. The showAdAfterPassScenes and showAdAfterPassTime are used as checking point when those two initial counters have been incremented and passed those values. If they have passed the fixed values we then show the advertisement. There is also a function called ChangeScene. This is used to add an increment of scene play when a user clicks a button to go to another scene. So just make sure when you switch a scene, you can use this function. Or if you have your own scene loader code, you can just call add an increment to AdInitiator.sceneCounter.

Let create the AdBanner.cs for Google Admob first.

using GoogleMobileAds.Api;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AdBanner : MonoBehaviour {

	// Use this for initialization
	void Start () {
		if(AdInitiator.lastActiveAdTime <= 0f)
        {
            AdInitiator.lastActiveAdTime = Time.time;
        }
        ShowAd();
    }
	
    private void ShowAd()
    {
		#if UNITY_ANDROID
			string adUnitId = "INSERT_ANDROID_INTERSTITIAL_AD_UNIT_ID_HERE";
		#elif UNITY_IPHONE
			string adUnitId = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE";
		#else
			string adUnitId = "unexpected_platform";
		#endif

		// Initialize an InterstitialAd.
		InterstitialAd interstitial = new InterstitialAd(adUnitId);
		
	   //***For Testing in the Device***
       // AdRequest request = new AdRequest.Builder()
       //.AddTestDevice(AdRequest.TestDeviceSimulator)       // Simulator.
       //.AddTestDevice("08fa70905f956ebb825f13aa9b652a6e")  // My test device.
       //.Build();
	   
		// Create an empty ad request.
		AdRequest request = new AdRequest.Builder().Build();
		// Load the interstitial with the request.
		interstitial.LoadAd(request);
		
		if (Utils.sceneCounter % noOfChangeScenes == 0 && Utils.sceneCounter >= noOfChangeScenes || Time.time - Utils.lastDisplayAdTime >= Utils.showAdTime)
        {
            if (interstitial.IsLoaded()) {
				interstitial.Show();
				AdInitiator.lastActiveAdTime = 0f;
				AdInitiator.sceneCounter = 0;
			}
        }
    }
}

In the start method, you can see I initiate the first lastActiveAdTime variable value if the initial value is equal or less than 0. Then in the ShowAd function, we create a check condition to see if lastActiveAdTime or number of play scenes have passed the designed check point values. And do not forget to reset back the AdInitiator variables to 0.

This is the next code for Unity ads. It will be called AdBanner.cs as well but with different code content.

using Assets.Scripts;
using GoogleMobileAds.Api;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Advertisements;

public class AdBanner : MonoBehaviour
{
    private string androidGameID = "xxxxxxx";

    // Use this for initialization
    void Start()
    {
        if(AdInitiator.lastActiveAdTime <= 0f)
        {
            AdInitiator.lastActiveAdTime = Time.time;
        }
		Advertisement.Initialize(androidGameID);
        ShowAd();
    }

    private void ShowAd()
    {
        if (Utils.sceneCounter % noOfChangeScenes == 0 && Utils.sceneCounter >= noOfChangeScenes || Time.time - Utils.lastDisplayAdTime >= Utils.showAdTime)
        {
            Advertisement.Show();
            Utils.lastActiveAdTime = 0f;
			AdInitiator.sceneCounter = 0;
        }
       
    }
}

I hope the sample code above helps you. If you want to see how it works, you can see download my app in the following link.

https://play.google.com/store/apps/details?id=com.andioapps.freetoddlerandbabygames

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Share your article with us and add your own google adsense account to earn extra money. Plus, you can promote a link back to your site.