- Home /
Question by
$$anonymous$$ · Aug 11, 2018 at 02:54 AM ·
admobunity ads
interstitial ad script error help need.
so I'm following instructions available on google's website, and this is what I wrote based on examples on that website
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
public class Advertisement : MonoBehaviour
{
private void Start ()
{
string appId = "xyz";
MobileAds.Initialize(appId);
}
private void RequestInterstitial()
{
string adUnitId = "xyz";
InterstitialAd interstitial = new InterstitialAd(adUnitId);
AdRequest request = new AdRequest.Builder().Build();
interstitial.LoadAd(request);
}
private void LoadAd()
{
if (interstitial.IsLoaded())
{
interstitial.Show();
Debug.Log("interstitial ad shown");
}
}
public void show() //added this function to a button
{
LoadAd();
}
}
script shows following error
private void LoadAd()
{
if (interstitial.IsLoaded())
{
interstitial.Show();
Debug.Log("interstitial ad shown");
}
}
in code above it says interstitial does not exist in current context, so I added
InterstitialAd interstitial;
on top of the script, then it shows following error 'object reference is not set to an instance'
Comment
Answer by madhav-aspiration · Aug 11, 2018 at 06:41 AM
public class AdsManager : MonoBehaviour { public static AdsManager Instanse;
public string AndroidInterstitalID; // use test ad id here
private InterstitialAd interstitial;
void Awake()
{
if (Instanse == null)
{
Instanse = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
void Start()
{
RequestInterstitialAds();
}
private void RequestInterstitialAds()
{
// Initialize an InterstitialAd.
interstitial = new InterstitialAd(AndroidInterstitalID);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// ads event add here
interstitial.OnAdOpening += Interstitial_OnAdOpened;
interstitial.OnAdClosed += Interstitial_OnAdClosed;
// etc...
// Load the interstitial with the request.
interstitial.LoadAd(request);
}
private void Interstitial_OnAdOpened(object sender, System.EventArgs e)
{
// pause game
Time.timeScale = 0;
}
private void Interstitial_OnAdClosed(object sender, System.EventArgs e)
{
// resume game
Time.timeScale = 1;
// new request
RequestInterstitialAds();
}
public void ShowInterstialAd(bool value)
{
if (interstitial.IsLoaded())
{
interstitial.Show();
}
else
{
RequestInterstitialAds();
}
}
}
Your answer