none
NullReferenceException: Object reference not set to an instance of an object (Unity) RRS feed

  • Question

  • Hi, I am Ayoub new to C# and unity at the start, plus I am doing this out of my interest, so my question could be basic. However it has bugged me for so long, that I couldn't get it over even after I research it over the internet.

    Please help me. thanks.

    console: NullReferenceException: Object reference not set to an instance of an object AdsManager.ShowAdMob () (at Assets/Scripts/AdsManager.cs:104) AdsManager.ShowInterstitial () (at Assets/Scripts/AdsManager.cs:54) Home.OnNormalMode () (at Assets/Scripts/Home.cs:86) UnityEngine.Events.InvokableCall.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:165) UnityEngine.Events.UnityEvent`1[T0].Invoke (.T0 arg0) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_1.cs:63) UnityEngine.EventSystems.EventTrigger.Execute (EventTriggerType id, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/EventTrigger.cs:67) UnityEngine.EventSystems.EventTrigger.OnPointerDown (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/EventTrigger.cs:93) UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerDownHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:36) UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerDownHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261) UnityEngine.EventSystems.EventSystem:Update()

    using UnityEngine;
     using System.Collections;
     using UnityEngine.UI;
     using GoogleMobileAds.Api;
     using System;
     using UnityEngine.Advertisements;
     
     public class AdsManager : MonoBehaviour {
     
         #region AdMob
         [Header("Admob")]
         public string adMobAppID;
         public string interstitalAdMobId;
         public string videoAdMobId;
         InterstitialAd interstitialAdMob;
         private RewardBasedVideoAd rewardBasedAdMobVideo; 
         AdRequest requestAdMobInterstitial, AdMobVideoRequest;
         #endregion
         [Space(15)]
         #region
         [Header("UnityAds")]
         public string unityAdsGameId;
         public string unityAdsVideoPlacementId = "rewardedVideo";
         #endregion
         public Text status;
         static AdsManager instance;
     
     
         public int interval;
         private int counter;
     
         private bool isDev = false;
         public static AdsManager Instance
         {
             get
             {
                 if(instance == null)
                     instance = GameObject.FindObjectOfType(typeof(AdsManager)) as AdsManager;
                 
                 return instance;
             }
         }
     
         void Awake ()
         {
             gameObject.name = this.GetType().Name;
             DontDestroyOnLoad(gameObject);
             InitializeAds();
         }
     
         public void ShowInterstitial()
         {
             if (isDev) return;
             ShowAdMob();
         }
     
         public void IsVideoRewardAvailable()
         {
             
         }
     
         public void ShowVideoReward()
         {
             if (isDev) return;
     
             if (rewardBasedAdMobVideo.IsLoaded())
             {
                 AdMobShowVideo();
             }
             else if (Advertisement.IsReady(unityAdsVideoPlacementId))
             {
                 UnityAdsShowVideo();
             }
             
        
             
         }
     
         private void RequestInterstitial()
         {
             // Initialize an InterstitialAd.
             interstitialAdMob = new InterstitialAd(interstitalAdMobId);
     
             // Called when an ad request has successfully loaded.
             interstitialAdMob.OnAdLoaded += HandleOnAdLoaded;
             // Called when an ad request failed to load.
             interstitialAdMob.OnAdFailedToLoad += HandleOnAdFailedToLoad;
             // Called when an ad is shown.
             interstitialAdMob.OnAdOpening += HandleOnAdOpened;
             // Called when the ad is closed.
             interstitialAdMob.OnAdClosed += HandleOnAdClosed;
             // Called when the ad click caused the user to leave the application.
             interstitialAdMob.OnAdLeavingApplication += HandleOnAdLeavingApplication;
     
             // Create an empty ad request.
             requestAdMobInterstitial = new AdRequest.Builder().Build();
             // Load the interstitial with the request.
             interstitialAdMob.LoadAd(requestAdMobInterstitial);
         }
     
         public void ShowAdMob()
         {
             if (isDev) return;
             if(interstitialAdMob.IsLoaded())
             {
                 interstitialAdMob.Show();
             }
             else
             {
                 interstitialAdMob.LoadAd(requestAdMobInterstitial);
                 counter++;
                 if(counter%interval==0)
                     UnityAdsShowVideo ();
             }
         }
     
         public void HandleOnAdLoaded(object sender, EventArgs args)
         {
             MonoBehaviour.print("HandleAdLoaded event received");
             status.text = args.ToString();
         }
     
         public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
         {
             MonoBehaviour.print("HandleFailedToReceiveAd event received with message: " + args.Message);
             status.text = args.Message;
         }
     
         public void HandleOnAdOpened(object sender, EventArgs args)
         {
             MonoBehaviour.print("HandleAdOpened event received");
         }
     
         public void HandleOnAdClosed(object sender, EventArgs args)
         {
             MonoBehaviour.print("HandleAdClosed event received");
             interstitialAdMob.LoadAd(requestAdMobInterstitial);
         }
     
         public void HandleOnAdLeavingApplication(object sender, EventArgs args)
         {
             MonoBehaviour.print("HandleAdLeftApplication event received");
         }
     
         private void RequestRewardedVideo()
         {
             // Called when an ad request has successfully loaded.
             rewardBasedAdMobVideo.OnAdLoaded += HandleRewardBasedVideoLoadedAdMob;
             // Called when an ad request failed to load.
             rewardBasedAdMobVideo.OnAdFailedToLoad += HandleRewardBasedVideoFailedToLoadAdMob;
             // Called when an ad is shown.
             rewardBasedAdMobVideo.OnAdOpening += HandleRewardBasedVideoOpenedAdMob;
             // Called when the ad starts to play.
             rewardBasedAdMobVideo.OnAdStarted += HandleRewardBasedVideoStartedAdMob;
             // Called when the user should be rewarded for watching a video.
             rewardBasedAdMobVideo.OnAdRewarded += HandleRewardBasedVideoRewardedAdMob;
             // Called when the ad is closed.
             rewardBasedAdMobVideo.OnAdClosed += HandleRewardBasedVideoClosedAdMob;
             // Called when the ad click caused the user to leave the application.
             rewardBasedAdMobVideo.OnAdLeavingApplication += HandleRewardBasedVideoLeftApplicationAdMob;
             // Create an empty ad request.
             AdMobVideoRequest = new AdRequest.Builder().Build();
             // Load the rewarded video ad with the request.
             this.rewardBasedAdMobVideo.LoadAd(AdMobVideoRequest, videoAdMobId);
         }
     
         public void HandleRewardBasedVideoLoadedAdMob(object sender, EventArgs args)
         {
             
             status.text = "Unity loaded";
     
         }
     
         public void HandleRewardBasedVideoFailedToLoadAdMob(object sender, AdFailedToLoadEventArgs args)
         {
             status.text = args.Message;
             MonoBehaviour.print("HandleRewardBasedVideoFailedToLoad event received with message: " + args.Message);        
         }
     
         public void HandleRewardBasedVideoOpenedAdMob(object sender, EventArgs args)
         {
            
         }
     
         public void HandleRewardBasedVideoStartedAdMob(object sender, EventArgs args)
         {
             MonoBehaviour.print("HandleRewardBasedVideoStarted event received");
         }
     
         public void HandleRewardBasedVideoClosedAdMob(object sender, EventArgs args)
         {
             MonoBehaviour.print("HandleRewardBasedVideoClosed event received");
             this.rewardBasedAdMobVideo.LoadAd(AdMobVideoRequest, videoAdMobId);
             status.text = "unity ad rewareded";
     
         }
     
         public void HandleRewardBasedVideoRewardedAdMob(object sender, Reward args)
         {
             GameController.Instance.UnlockSong();
             this.rewardBasedAdMobVideo.LoadAd(AdMobVideoRequest, videoAdMobId);
     
         }
         public void HandleRewardBasedVideoLeftApplicationAdMob(object sender, EventArgs args)
         {
             MonoBehaviour.print("HandleRewardBasedVideoLeftApplication event received");
         }
     
         void InitializeAds()
         {
             MobileAds.Initialize(adMobAppID);
             this.rewardBasedAdMobVideo = RewardBasedVideoAd.Instance;
             this.RequestRewardedVideo();
             Advertisement.Initialize(unityAdsGameId);
             RequestInterstitial();
         }
     
     
         void AdMobShowVideo()
         {
             rewardBasedAdMobVideo.Show();    
         }
     
         void UnityAdsShowVideo()
         {
             ShowOptions options = new ShowOptions();
             options.resultCallback = HandleShowResultUnity;
     
             Advertisement.Show(unityAdsVideoPlacementId, options);
         }
     
         void HandleShowResultUnity(ShowResult result)
         {
             if (result == ShowResult.Finished)
             {            
                 GameController.Instance.UnlockSong();
                 Advertisement.Initialize(unityAdsGameId);
             }
             else if (result == ShowResult.Skipped)
             {
                 Debug.LogWarning("Video was skipped - Do NOT reward the player");
     
             }
             else if (result == ShowResult.Failed)
             {
                 status.text = "unity failed";
             }
             
         }
     
         bool isVideoAvaiable()
         {
     #if !UNITY_EDITOR
             if(Advertisement.IsReady(unityAdsVideoPlacementId))
             {
                 return true;
             }
             else if(rewardBasedAdMobVideo.IsLoaded())
             {
                 return true;
             }
     #endif
             return false;
         }
     }

    Wednesday, August 1, 2018 2:29 PM

All replies

  • If i'm reading this right, the issue is in the ShowAdMob() function, where you are calling a method on interstitialAdMob, but this variable is presumably null.

    Now interstitialAdMob is created in RequestInterstitial(), which is called from InitializeAds(), which is called from Awake().

    So.

    Perhaps ShowAdMob() is getting called before the Awake() method (or any of the other functions in the chain)?

    Have you tried just setting breakpoints in ShowAdMob and the other functions to see what order they are getting called and where they are called from?

    Wednesday, August 1, 2018 2:45 PM
  • Please can you write me the code to understand better?

    Thanks.

    Wednesday, August 1, 2018 4:36 PM
  • Please can you write me the code to understand better?

    Thanks.

    console: NullReferenceException: Object reference not set to an instance of an object AdsManager.ShowAdMob () (at Assets/Scripts/AdsManager.cs:104)

    Class vs object vs instance 

    When a class is instanced into a object, the object lives in memory. If the class has not been instanced into memory, then it's a null value object that is not there.

    If code to tries to use a object that is not there in memory, Object reference not set to an instance of an object

    It's OO 101 here that you should know.

    https://alfredjava.wordpress.com/2008/07/08/class-vs-object-vs-instance/

    You are being told what class and at what line number the error occurred.

    1) Use Google and find out how to turn on Line Numbers in Visual Stuido

    2) Learn how to use the Visual Stuido Debugger 

    https://docs.microsoft.com/en-us/visualstudio/debugger/getting-started-with-the-debugger

    3) Learn how to use the debugger Quickwatch to find out what object is a null valute

    Then it's up to you to find out, debug the code,  why the object is a null value object.

    Wednesday, August 1, 2018 7:52 PM
  • Greetings Ayoub9911.

    In general, a NullReferenceException means you have done something like this...

    MyClass mc;
    mc.DoSomething();  // This line will give an error.

    ... instead of this...

    MyClass mc = new MyClass();
    mc.DoSomething(); // This works because we did a "new".
    
    
    // Or this
    MyClass mc;
    mc = new MyClass(); // We can do the "new" on another line.
    mc.DoSomething(); 

    What RJP1973 is saying is that the "new" on interstitialAdMob is supposed to happen in RequestInterstitial() before you get to ShowAdMob(), so if is not being called the "new" won't happen and you will get the error.

    So you need to make sure RequestInterstitial() is being called before ShowAdMob() is called.

    Does that help?

    Thursday, August 2, 2018 1:47 AM
  • In my opinion, the script probably has no errors, because on another PC where it was created it worked.
    do you think it's just a script error?
    Thursday, August 2, 2018 2:28 PM
  • In my opinion, the script probably has no errors, because on another PC where it was created it worked.
    do you think it's just a script error?

    Well, if you are getting an error then your opinion is wrong. Or the error is that the methods in this script are now being called in a different order, as I suggested in my original post above.

    Have you followed any of the other posters advice, such as DA924x or Ante Meridian?

    Do you understand that an object must be instantiated (i.e. created) before it can be used?

    Have you looked into how to set debug points so you can run your program, test your variables and see the order of execution?

    Friday, August 3, 2018 7:03 AM
  • I tried to debug, I hope I ran it well ... anyway it's like you see in the screenshot interstitialAdMob is null ...
    now I do not know how to continue.

    Screenshot: https://social.msdn.microsoft.com/Forums/getfile/1300814

    Friday, August 3, 2018 9:27 AM
  • Your screenshot just confirms what we have all already told you:

    That ShowAdMobs() is being called but your interstitialAdMob variable is still null.

    This interstitialAdMob variable is only created in a completely different function RequestInterstitial().

    In other words, your AdsManager class is written in such a way that it requires RequestInterstitial to be called first, in order to initialize the various variables, before ShowAdMobs() is called.

    This is not happening.

    I cannot tell you why, because either this class has been designed incorrectly, or the problem is with some other part of your program which should be calling your AdsManager class functions in a different order (or its not calling them at all when it should be).

    Hence you have to look through your code, find the places that use the AdsManager class, use the debugger and step through if necessary, and figure out if the calling code is doing something wrong such as not calling a function that it should be calling, etc.

    This is all going to depend on how your entire program is designed, so probably not something anyone will be able to give you a simple answer to just from this one script.



    • Edited by RJP1973 Friday, August 3, 2018 10:10 AM clarifying paragraph
    Friday, August 3, 2018 9:36 AM