Admob unity rewarded videos not working - android

I was using Unity ads on my android game and everything was working perfectly, except from some devices where Unity ads where not showing sometimes. So, I wanted to test Admob rewarded video to see if I could get a better performance. Here's the code I'm using for Admob:
public void RequestRewardBasedVideo()
{
#if UNITY_EDITOR
string adUnitId = "unused";
#elif UNITY_ANDROID
string adUnitId = "ca-app-pub-243186545632812xxxxxxxxxxxx";
#elif UNITY_IPHONE
string adUnitId = "unused";
#else
string adUnitId = "unexpected_platform";
#endif
RewardBasedVideoAd rewardBasedVideo = RewardBasedVideoAd.Instance;
AdRequest request = new AdRequest.Builder().Build();
rewardBasedVideo.LoadAd(request, adUnitId);
showAdvertisment(rewardBasedVideo);
}
private void showAdvertisment(RewardBasedVideoAd rewardBasedVideo)
{
if (rewardBasedVideo.IsLoaded())
{
rewardBasedVideo.Show();
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
//reward
}
I assigned the RequestRewardBasedVideo() to a button, but the issue is that the videos are not showing! I think I'm in the right path because when I click the button, the console logs:
Dummy .ctor
Dummy CreateRewardBasedVideoAd
Dummy LoadAd
Dummy IsLoaded
Dummy ShowRewardBasedVideoAd
I have already tried putting the app on my Android device and imported the Google Admob package for Unity, also configured the ads in the Admob panel. Anyone have any ideas for what I can do to solve this??

It may be due to no reward video or no ad video available currently. Try testing with test ads. Do include test device ID in your request code like this:
AdRequest request = new AdRequest.Builder()
.AddTestDevice("34343")
.Build();
Try with sample ad UNIT Id. Hopefully it works.

Your code is wrong. You should separate request ad and show ad into two functions. In Start() function, you call request function and show ad function should be hooked into your button. It's because when you request ad, it'll take some time to make ad available for you.

what if video isn't loaded? You need to handle that case, listen to load event and then hit show.
if (rewardBasedVideo.IsLoaded())
{
rewardBasedVideo.Show();
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}else{
rewardBasedVideo.OnAdLoaded += HandleVideoLoaded;
}
public void HandleVideoLoaded(object sender, Reward args)
{
rewardBasedVideo.Show();
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
rewardBasedVideo.OnAdRewarded -= HandleRewardBasedVideoRewarded;
}

Related

Unity Ads 4.0 - Multiple OnUnityAdsShowComplete Callbacks for Rewarded ads

Using the Rewarded ad script found on the Unity Ads SDK, I'm running into an issue where the ShowAd() IUnityAdsShowListener => OnUnityAdsShowComplete is firing the debug log incrementally. The first Ad I watch returns one line stating the ad is completed, the second Ad I watch, fires off 2 logs, the third 3, then 4, etc...As if each ShowAd() subscribes a new listener to the callback. is this normal?
Im not using a button to call the ShowAd method, rather I'm just calling a function with a delegate from an AdsManager class.
public delegate void OnSuccessfulAd();
private OnSuccessfulAd _myCallback = null;
public void ShowAd(OnSuccessfulAd myMethod)
{
_myCallback = myMethod;
Advertisement.Show(_adUnitId, this);
}
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
{
if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
{
Debug.Log("Unity Ads Rewarded Ad Completed"); //Gets called more times each ad
// Grant a reward.
_myCallback?.Invoke();
}
}
Experiencing the same issue. As a temporary solution I nullify _myCallback after invoking it
I am working on the Ads 4.0.0 version in Unity.
What I observed even for Button Click is that its giving multiple Logs in Unity Editor.
However if I run the Code in my mobile Build its working as expected only 1 Log gets generated and Reward also remains same on multiple ad watches.
The issues seems to be in the CallBack in unity, My suggestion would be Try the Build in your App Once Hopefully that fixes the issue.
Unity Rewarded Ads Code from Official Page
As Unity has Deprecated most of the Previous Listeners in the New Ads 4.0.0 I think its better to cross check in the Build.
I was facing the exact same issue.
My OnUnityAdsShowComplete event callback is invoking one of my delegate.
Every references in my delegate was not accessible.
Look like the OnUnityAdsShowComplete is done on a different thread than the main one.
If in your delegate callback you have a simple Time.timeScale=1f, this should cause a crash since Time is no reachable.
Also this has observable only with reward Ads type.
My solution was to call the show() method inside a coroutine.
By having a flag set i.e. isAdRunning
You can poll that flag and when the flag is false isAdRunnin = false then you can call your delegate.
Very annoying.
Here an example. To make the code the simpliest as possible. All the IUnityAds interfaces are in the same class. This is why you will see this as listener arguments.
using UnityEngine.Advertisements;
private bool isAdsRunning = false;
// Ads start callback
public void OnUnityAdsShowStart(string placementId)
{
isAdsRunning = true;
}
// Ads complete callback
public void OnUnityAdsShowComplete(string placementId, UnityAdsShowCompletionState showCompletionState)
{
isAdsRunning = false;
}
// Entry point to show reward ads
public void ShowRewardedAd()
{
StartCoroutine(RewardRoutine());
}
IEnumerator RewardRoutine()
{
while (Advertisement.isShowing)
{
yield return null;
}
// In 4.0 Ads need to be loaded first, after initialization
// just another flag to make sure everything is initialized :)
while (!isAdLoaded)
{
yield return null;
}
// Show Ads
Advertisement.Show(adsUnitIdReward, this);
yield return new WaitForSeconds(0.25f);
while(isAdsRunning)
{
yield return null;
}
// My custom delegate
AdAction.Invoke();
}
Peace and Love.

AdMob RewardBasedVideoAd, App crash after reward video closed (Unity3dd, Android)

I'm working on an Android game and I want to add AdMob ads to my game. I have added Banner and interstitial Views but the problem in RewardBasedVideoAd specifically on OnAdRewarded event, when the user closes the video return to the game to earn his reward game crash immediately.
After many tries, I found the code which crashes the game, gameObject.SetActive(true) And gameObject.SetActive(false), is the problem, when I deactivate game panel UI and active reward panel UI game crash immediately.
How can I solve it? why game crash when I use gameObject.SetActive ?
code which make app crashed
public void HandleOnAdRewarded(object sender, EventArgs args)
{
gamePanel.SetActive(false);
rewardPanel.SetActive(true);
}
request reward code
public void RequestReward()
{
AdRequest request = new AdRequest().Builder().Build();
this.rewardAd.LoadAd(request, rewardAdId);
rewardAd.OnAdLoaded += this.HandleOnRewardAdLoaded;
rewardAd.OnAdRewarded += this.HandleOnAdRewarded;
rewardAd.OnAdClosed += this.HandleOnRewardAdClosed;
}
handlers
public void HandleOnRewardAdLoaded(object sender, EventArgs args)
{
if(rewardAd.IsLoaded())
{
rewardAd.Show();
}
}
public void HandleOnAdRewarded(object sender, EventArgs args)
{
gamePanel.SetActive(false);
rewardPanel.SetActive(true);
}
public HandleOnRewardAdClosed(object sender, EventArgs args)
{
rewardAd.OnAdLoaded -= this.HandleOnRewardAdLoaded;
rewardAd.OnAdRewarded -= this.HandleOnAdRewarded;
rewardAd.OnAdClosed -= this.HandleOnRewardAdClosed;
}
for anyone has this issue
the cause of the problem is TextMesh Pro package
JUST UNINSTALL IT.
I had the same issue and in my case i was changing UI and sending requests to server after OnAdClosed and OnRewardEarned and so the crash happens when i close the ad.
I think that the reason is that these changes actually apply before coming back to the app and in that time the app is Paused. So i fixed it by using bool to know that if OnAdClosed and OnRewardEarned are called that then change UI and send requests in OnApplicationPause function like the code below.
Note: I send analytics events in OnAdClosed and OnRewardEarned and they work fine without any problem or crash.
private void OnApplicationPause(bool isPaused)
{
if (!isPaused)
{
if (_isRewardEarned)
{
_onEarnedRewardEvent?.Invoke();
}
if (_isRewardedAdClosed)
{
_onRewardedAdClosedEvent?.Invoke();
InitializeNextRewardedAd();
}
}
}

google loads native ad banner only once

I'm implementing google native ads on android.Most of the code I copy/pasted from this example
The only difference is I request bunch of ads instead of one ad.Here is load function:
public void loadAds(String unitId,int count) {
if (nativeAds.size()>0) {
for(UnifiedNativeAd ad: nativeAds)
ad.destroy();
}
nativeAds =new ArrayList();
//load
AdLoader.Builder builder = new AdLoader.Builder(context, unitId);
builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
// OnUnifiedNativeAdLoadedListener implementation.
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd nativeAd) {
// You must call destroy on old ads when you are done with them,
// otherwise you will have a memory leak.
//nativeAd = unifiedNativeAd;
int numAds =nativeAds.size();
int insertTo=numAds==0? firstAdPosition : firstAdPosition +numAds*(AdStep +1);
CategoryData item = new CategoryData();
item.type = ItemData.TYPE_CATEGORIES_NATIVE_AD;
if (insertTo<data.size())
data.add(insertTo, item);
item = new CategoryData();
item.type = ItemData.TYPE_CATEGORIES_SEPARATOR;
if (insertTo<data.size())
data.add(insertTo+1, item);
nativeAds.add(nativeAd);
Log.d("nativead","got ad body "+nativeAds.size()+":"+nativeAd.getBody());
notifyItemRangeInserted(insertTo,2);
}
});
VideoOptions videoOptions = new VideoOptions.Builder()
.setStartMuted(true)
.build();
NativeAdOptions adOptions = new NativeAdOptions.Builder()
.setVideoOptions(videoOptions)
.build();
builder.withNativeAdOptions(adOptions);
AdLoader adLoader = builder.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
Log.d("nativead","error code " +errorCode);
/*
Toast.makeText(context, "Failed to load native ad: "
+ errorCode, Toast.LENGTH_SHORT).show();
*/
}
}).build();
AdRequest adRequest;
// get unpersonalized ads if needed
if(AppModel.getAppData().gdpr.eea && AppModel.getAppData().gdpr.consentStatus!= ConsentStatus.PERSONALIZED) {
Bundle extras = new Bundle();
extras.putString("npa", "1");
adRequest = new AdRequest.Builder().addNetworkExtrasBundle(AdMobAdapter.class,extras).build();
} else {
adRequest = new AdRequest.Builder().build();
}
adLoader.loadAds(adRequest,count);
//adLoader.loadAd(adRequest);
}
First time it loads ok, but if I restart the app it throws a bunch of errors:
I/Ads: Received log message: The ad request returned a no fill for the particular slot. The error log below that says 'Malformed native JSON response' is a benign warning that will be removed in a future SDK release.
Also error code 0 is passed into onAdFailedToLoad.If I clear app's data banners are loaded again but again only for single run
As you mentioned, in the comment above, you're testing it on real ad units (which is quite dangerous as you might get blocked for that).
You're getting NO_FILL, which means there is no inventory left to serve in the AdMob backend.
You can find out more about this issue (not an issue, we can call it a "thing") here.
To get proper results, always test with test ads, so that you get maximum fill rate for the ads while testing.
You'll find the ad unit ID's for test ads on this page.
And, if you still get NO_FILL error a lot in production, try using mediation to get ads from multiple ad sources. You'll never get 100% fill rate for your ads, though, so make sure you code accordingly to handle the NO_FILL.
Also, one more reminder, do not use live ads to test the app, you might get blocked by Admob/Google for doing that.

Unity RewardedVideoAds not working

Hello I am trying to implement Admob with unity, I have successfully integrated banner ads and Interstitial ads using the Test ids provided by Admob over here https://developers.google.com/admob/android/test-ads. How ever I am unable to display any rewarded Video ads. When ever I call the RewardedVidosAds nothing shows up and a debug log error displays Ad not ready. This is the following code I am using:
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using GoogleMobileAds;
using GoogleMobileAds.Api;
public class AdManager: MonoBehaviour {
public RewardBasedVideoAd rewardBasedVideoAd;
private InterstitialAd fullAdmob;
private bool rewardBasedEventHandlersSet = false;
// reward initialized
public int scoreAmount = 100;
// Use this for initialization
void Start() {
//loading both rewarded and interstitial ads in start.
LoadRewardBasedAd();
//RequestFull ();
}
// Update is called once per frame
void Update() {
}
public void LoadRewardBasedAd() {
rewardBasedVideoAd = RewardBasedVideoAd.Instance;
//Test
AdRequest adRequest = new AdRequest.Builder()
.Build();
rewardBasedVideoAd.LoadAd(adRequest, "ca-app-pub-3940256099942544/5224354917");
}
public void ShowRewardBasedAd() {
if (rewardBasedVideoAd.IsLoaded()) {
Debug.Log("Showiung video");
rewardBasedVideoAd.Show();
} else Debug.Log("not ready");
}
}
I have not currently mediated my video Ads could this be causing the problem? I read that you dont need to mediate your ads if your using a test AdId. I also get the following errors in my logcat when calling for a rewardedVideoAd
Fail to instantiate adapter com.google.DummyAdapter
Fail to load ad:3

Interstitial Ads not showing admob plugin for unity

I am trying to put an interstitial ad after every 5 games the user plays. What I've done is created an empty object with the following script:
using UnityEngine;
using GoogleMobileAds.Api;
public class AdBetweenGames : MonoBehaviour {
InterstitialAd interstitial;
void Start()
{
if(PlayerPrefs.GetInt("games-played", -1) % 5 == 0)
{
this.ShowInterstitial();
}
}
private void RequestInterstitial()
{
string adUnitId = "UNITID";
// Initialize an InterstitialAd.
interstitial = new InterstitialAd(adUnitId);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
interstitial.LoadAd(request);
}
public void ShowInterstitial()
{
RequestInterstitial();
Debug.Log("Interstatial ad called.");
if (interstitial.IsLoaded())
{
interstitial.Show();
}
}
}
I am sure the code here is called properly based on the debug log. I've also tried doing banner ads and they show without a problem after 1-2 seconds. I am making an android game.
Also I was thinking, could it be that the ad needs some extra time to load and I am clicking try again too early. But then what would a solution be?
The interstitial ad of ad mob need time to load try it in update and wait for at least 4 sec and call ShowInterstitial function inside a bool set its value true in start and false it after calling the function to show ad once.

Categories

Resources