Search Unity

Object reference not set to an instance of an object

Discussion in 'Editor & General Support' started by ituraspe, Mar 27, 2019.

  1. ituraspe

    ituraspe

    Joined:
    Jan 1, 2019
    Posts:
    27
    Hi, when I want to add AdMob Interstitial ads for test I get this error
    "NullReferenceException: Object reference not set to an instance of an object"


    Here is my code:


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using GoogleMobileAds.Api;
    5.  
    6. public class GoogleFullScreen : MonoBehaviour
    7. {
    8.     private InterstitialAd interstitial;
    9.  
    10.     void Start()
    11.     {
    12.         if (this.interstitial.IsLoaded())
    13.         {
    14.             this.interstitial.Show();
    15.         }
    16.     }
    17.  
    18.     private void RequestInterstitial()
    19.     {
    20.     #if UNITY_ANDROID
    21.         string adUnitId = "ca-app-pub-3940256099942544/1033173712";
    22.     #elif UNITY_IPHONE
    23.         string adUnitId = "ca-app-pub-3940256099942544/4411468910";
    24.     #else
    25.         string adUnitId = "unexpected_platform";
    26.     #endif
    27.  
    28.     // Initialize an InterstitialAd.
    29.     this.interstitial = new InterstitialAd(adUnitId);
    30.     // Create an empty ad request.
    31.     AdRequest request = new AdRequest.Builder().Build();
    32.     // Load the interstitial with the request.
    33.     this.interstitial.LoadAd(request);
    34.     }
    35. }
    36.  
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,281
  3. ituraspe

    ituraspe

    Joined:
    Jan 1, 2019
    Posts:
    27
    "NullReferenceException: Object reference not set to an instance of an object
    GoogleFullScreen.Start () (at Assets/GoogleFullScreen.cs:12)"
     
  4. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,281
    interstitial is null. Looks like you need to call RequestInterstitial().
    Code (csharp):
    1. void Start()
    2. {
    3.     RequestInterstitial();
    4.     if (this.interstitial.IsLoaded())
    5.     {
    6.         this.interstitial.Show();
    7.     }
    8. }
     
    ituraspe likes this.
  5. ituraspe

    ituraspe

    Joined:
    Jan 1, 2019
    Posts:
    27
    thank you, it works