简体   繁体   中英

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.

In this part

#if UNITY_ANDROID
    appID = "ca-app-pub-3940256099942544/5224354917";
#elif UNITY_IPHONE
    appID = "ca-app-pub-3940256099942544/5224354917";
#else
    appID = "Probably Pc";
#endif

It should be should Ad unit ID not App ID. Check this Admob Unity tutorial if you need more help.

Fixed my issue by Force Resolving:

Assets > External Dependency Manager > Android Resolver > Force Resolve

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM