AdMob interstitial ads problem

Hi.
Can’t figure out one thing, that looks like should be simple… but I am missing something.

I want to use interstitial ads instead of banner.
I use my menu script to hold ad script. Works ok for banner ads.
Here is what it looks like with interstitial:

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

public class menuScript : MonoBehaviour {

    InterstitialAd interstitial;

    private void Start()
    {
        RequestInterstitial ();
    }

    public void StartLevel ()
    {
        Application.LoadLevel (1);
    }

    private void RequestInterstitial()
    {
        #if UNITY_ANDROID
        string adUnitId = "ca-app-pub-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        #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);
        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder().Build();
        // Load the interstitial with the request.
        interstitial.LoadAd(request);
    }

    public void ExitGame ()
    {
        if (interstitial.IsLoaded()) {
            interstitial.Show();
        }
    }
}

I use Exit button (ExitGame) for now to test ad.
It loads ad ok as far as I see:

Created DummyClient
UnityEngine.Debug:Log(Object)
Dummy CreateIntersitialAd
UnityEngine.Debug:Log(Object)
Dummy LoadAd
UnityEngine.Debug:Log(Object)

But when I press button to show ad:

NullReferenceException: Object reference not set to an instance of an object
menuScript.ExitGame () (at Assets/Scripts/menuScript.cs:40)

It does work:

Dummy IsLoaded
UnityEngine.Debug:Log(Object)
Dummy ShowInterstitial
UnityEngine.Debug:Log(Object)

:when I put it inside “private void RequestInterstitial()” after “interstitial.LoadAd(request);”. But of course that doesn’t work for me since I need to pre-load the ad and show it on game over.

Also it doesn’t like the InterstitialAd interstitial;…

warning CS0649: Field menuScript.interstitial' is never assigned to, and will always have its default value null’

but I need it for “if (interstitial.IsLoaded()) { interstitial.Show(); }” to work.

So what I am doing wrong? How you would do it?
All I need is basic ad on game over.

You need to check interstitial for being != null first. You are calling the .isLoaded() method on a null pointer.

1 Like