IMG-LOGO

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

andy - 14 Sep, 2017 8145 Views 7 Comment
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 noOfChangeScenes = 10;
		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 download my unity app in the following link.

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

Comments

Amit
27 Dec, 2018
Nice, Can you please let me know how can I place interstitial ad on game startup,means when a user click app icon, first add will load then main menu. I hope you will help me
andy
27 Dec, 2018
Hi Amit, if you want to show in initial startup without the timer, in the if condition under ShowAd() method, you can create a flag boolean that has an initial false. Once the ad has been showed, you set the flag to true. It will then show the ad after the initial icon or game has been loaded.
yazen
02 Jan, 2019
hi Andy I have a game to re-skin it and I want to change the number of value of showing ads after every game over and I don't know how to find the way to change it please help me.
andy
04 Jan, 2019
There is a class called AdInitiator, where you can set the variable showAdAfterPassScenes value to a specific number. This number is used to determine if the scenes have reached this value, it will then load the advertisement banner. You need to change a bit of the logic in here, instead of counting the number of scenes that have been loaded by the game, you can add the counter at the end of the game is over. Let me know if I did not get your question right.
Cornelius Mugabi
31 May, 2019
Hi Andy, Your code has errors. eg in AdBanner.cs Error: The name noOfChangeScenes does not exist in the current context Error: does not contain a definition for sceneCounter
andy
31 May, 2019
You are right. I just add it as a public variable ;-)
Yassin
13 Aug, 2019
Hi, I'm implemented Admob Ads in source code and i'm separated the games levels by scenes, i'm simply created a button of game success with a simple code to go in to the next level which mean the next scene, but i didn't got it to show the interstitial in this step as normal code that i use normally, the thing is just inside the same scene that the interstitial can working, here's that i'm using public void NextLevelbtn() { AdManager.Instance.Invoke("RequestInterstitial", 0.5f); SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); Time.timeScale = 1f; } Note : i'm preparing ShowInterstitial before Can you help me please ?
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles