Search code examples
androidunity-game-engineadmobnullreferenceexceptionlogcat

Unity AdMob reward ad runs normally, but gets a NullReferenceException on android


I implemented Admob rewarded ads and they work perfectly in unity, but when building and running the game on my Android the ad doesn't run.

This is the LogCat error

This is the code when I run the WatchAd(int ID) the game seems to get stuck on rewardedAd.IsLoaded()

private RewardedAd rewardedAd;
public void Start()
{
    MobileAds.Initialize(HandleInitComplete);
    rewardPopUp.SetActive(false);
    CreateAndLoadRewardedAd();
}
private void HandleInitComplete(GoogleMobileAds.Api.InitializationStatus status) =>
#if UNITY_ANDROID
    appID = "ca-app-pub-3940256099942544/5224354917";
#elif UNITY_IPHONE
    appID = "ca-app-pub-3940256099942544/5224354917";
#else
    appID = "Probably Pc";
#endif
public void WatchAd(int ID)
{
    Debug.Log("Ran WatchAD");
    if (rewardedAd.IsLoaded())
    {
        Debug.Log("IsLoaded");
        rewardedAd.Show();
        rewardPopUp.SetActive(true);
        AdType = ID;
    }
    else { 
        CreateAndLoadRewardedAd(); 
        Debug.Log("Can't Load");}
}
public void CreateAndLoadRewardedAd()
{
    rewardedAd = new RewardedAd(appID);

    rewardedAd.OnAdFailedToLoad += HandleRewardedAdFailedToLoad;
    rewardedAd.OnAdFailedToShow += HandleRewardedAdFailedToShow;
    rewardedAd.OnUserEarnedReward += HandleUserEarnedReward;

    AdRequest request = new AdRequest.Builder().Build();
    rewardedAd.LoadAd(request);
}
public void HandleRewardedAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
    switch (timesFailed)
    {
        case 0:
            Invoke("CreateAndLoadRewardedAd()", 60);
            break;
        case 1:
            Invoke("CreateAndLoadRewardedAd()", 120);
            break;
        default:
            Invoke("CreateAndLoadRewardedAd()", 240);
            break;
    }
    timesFailed++;
}

I Have tried doing this with test ads and my own AdMob ad IDs, also added my device as a test device. there are no errors displayed when i run it with unity.


Solution

  • Fixed my issue by Force Resolving:

    Assets > External Dependency Manager > Android Resolver > Force Resolve