How to Show Admob Interstitials on Counted Click? - unity3d

I am trying to something like this:
if button clicked for 4 times, I could show Interstitial?
However i couldn't make it happen.
Created a game object.
Attached script to that object.
Created a restart button.
Implemented this object on that button with onclick-runtime only etc.
Now every time user clicks restart button, interstitial ads show itself. but of course as you might know, it is very annoying.
I dont know how to count how many times users press the restart button and for example show the ads every 3 or 4 times if user press the button.
Thank you.
using UnityEngine;
using System.Collections;
using GoogleMobileAds.Api;
public class AdScript : MonoBehaviour
{
InterstitialAd interstitial;
public string InterstitialId;
// Use this for initialization
void Start()
{
//Request Ads
//RequestBanner();
RequestInterstitial();
}
public void showInterstitialAd()
{
//Show Ad
if (interstitial.IsLoaded())
{
interstitial.Show();
}
}
private void RequestInterstitial()
{
string adUnitId = InterstitialId;
// 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);
}
}

I can give you idea ,you can use time class to know last showed ad or use variable saying like every 4 game show ad on restart button click.
using UnityEngine;
using System.Collections;
using GoogleMobileAds.Api;
public class AdScript : MonoBehaviou
{
int counter =0;
InterstitialAd interstitial;
public string InterstitialId;
// Use this for initialization
void Start()
{
//Request Ads
//RequestBanner();
RequestInterstitial();
}
public void showInterstitialAd()
{
counter ++;
if(counter%4==0)
{
//Show Ad
if (interstitial.IsLoaded())
{
interstitial.Show();
}
}
}
private void RequestInterstitial()
{
string adUnitId = InterstitialId;
// 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);
}
}

Related

The gameobject has been destroyed but you are still trying to access it

I am trying to make a unity ad so that when the player loses, he can watch an ad to continue. However, when i change scenes and try to watch the ad again, it shows the gameobject which is the HeartMenu.SetActive(false) has been destroyed but you are still trying to access it but my script just sets the heart menu to SetActive(false). How can i go around this?
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
public class RewardedAdsButton : MonoBehaviour,
IUnityAdsLoadListener, IUnityAdsShowListener
{
[SerializeField] Button _showAdButton;
[SerializeField] string _androidAdUnitId =
"Rewarded_Android";
[SerializeField] string _iOSAdUnitId = "Rewarded_iOS";
string _adUnitId = null; // This will remain null for
unsupported platforms
public GameObject Restart;
public GameObject HeartMenu;
void Awake()
{
#if UNITY_IOS
_adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
_adUnitId = _androidAdUnitId;
#endif
}
public void Update()
{
}
// Load content to the Ad Unit:
public void LoadAd()
{
// IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
Debug.Log("Loading Ad: " + _adUnitId);
Advertisement.Load(_adUnitId, this);
}
// If the ad successfully loads, add a listener to the button and enable it:
public void OnUnityAdsAdLoaded(string adUnitId)
{
Debug.Log("Ad Loaded: " + adUnitId);
if (adUnitId.Equals(_adUnitId))
{
// Configure the button to call the ShowAd() method when clicked:
_showAdButton.onClick.AddListener(ShowAd);
// Enable the button for users to click:
_showAdButton.interactable = true;
}
}
// Implement a method to execute when the user clicks the button:
public void ShowAd()
{
// Disable the button:
_showAdButton.interactable = false;
// Then show the ad:
Advertisement.Show(_adUnitId, this);
}
// Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
{
if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
{
Debug.Log("Unity Ads Rewarded Ad Completed");
// Grant a reward.
HeartMenu.SetActive(false);
OnDestroy();
Time.timeScale = 1f;
// Load another ad:
Advertisement.Load(_adUnitId, this);
}
}

Ads not working on the production build of android game

I made an android game. I added some ads on it with the test mode off and than I released the game to internal testers and the ads were working so than I fixed some issues in game and released the game for production on playstore.
Now that the game is up on Playstore ads are not working. Will it take some time for ads to show up? There was a popup on unity monetization dashboard that I need to update package name and I did it but ads are still not showing up although playstore listing shows that my app contain ads.
My code is :
public string gameId = "ihavemygameidhere";
public bool testMode = true;
void Start()
{
// Initialize the Ads service:
Advertisement.Initialize(gameId, testMode);
}
public void ShowInterstitialAd()
{
// Check if UnityAds ready before calling Show method:
if (Advertisement.IsReady())
{
Advertisement.Show();
}
else
{
Debug.Log("Interstitial ad not ready at the moment! Please try again later!");
}
}
When the ad is not ready, that means that the ad server has not yet sent an ad to be seen. I would recommend placing the IsReady() check in a Coroutine, then showing a loading screen UI when the player is waiting. I would also put a fail of some amount of time in case the IsReady() always fails.
[SerializeField] private GameObect LoadingUI = null;
private float waitTime = 5f;
public void ShowInterstitialAd()
{
StartCoroutine(ShowAd());
}
private IEnumerator ShowAd()
{
float currentTime = 0.0f;
LoadingUI.SetActive(true);
while(currentTime <= waitTime && !Advertisement.IsReady())
{
currenTime += Time.deltaTime;
yield return null;
}
// show the ad if it is now ready
if(Advertisement.IsReady())
{
Advertisement.Show();
}
else
{
Debug.LogError("Error: Ad was not able to be loaded in " + waitTime + " seconds!");
}
LoadingUI.SetActive(false);
}
Make sure to assign some object in the inspector for the LoadingUI object so players can not tap to view ads again or just some UI that blocks all input while the ad is attempting to load. I would use a ScreenOverlay UI as it would be rendered over everything.

Unity + Admob rewarded ads : event not firing

I am stuck with admob rewarded ads, i can't figurate how to make event working. The problem is that my quiz game reload the scene every questions and even if i prevent the ad from destroy, the event are not firing at all. The ads are showing perfectly. I have tried multiple things but i must make a mistake somewhere... Anyone have an idea ?
Thank you very much!
using System;
using System.Collections;
using UnityEngine;
using GoogleMobileAds.Api;
public class RewardedScriptRow : MonoBehaviour
{
private RewardBasedVideoAd rewardBasedVideo;
public AudioClip GiftSound;
// Use this for initialization
void Start()
{
RequestInterstitial();
Debug.Log("Load at start");
}
public void LaunchAd() //Called from another script
{
StartCoroutine("Load");
}
private void RequestInterstitial()
{
string adUnitId = "";
#if UNITY_ANDROID
adUnitId = "ca-app-pub-00000/00000000";
#elif UNITY_IOS
adUnitId = "ca-app-pub-0000000000000";
#else
adUnitId = "unexpected_platform";
#endif
// Get singleton reward based video ad reference.
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
this.rewardBasedVideo.LoadAd(request, adUnitId);
rewardBasedVideo.OnAdFailedToLoad += HandleRewardBasedVideoClosed;
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
IEnumerator Load()
{
while (!rewardBasedVideo.IsLoaded())
yield return new WaitForEndOfFrame();
yield return new WaitForSeconds(0.0f);
rewardBasedVideo.Show();
yield break;
}
//EVENT
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
GetComponent<AudioSource>().PlayOneShot(GiftSound, 1.0F);
RequestInterstitial();
}
public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
{
GetComponent<AudioSource>().PlayOneShot(GiftSound, 1.0F);
RequestInterstitial();
}
}
EDIT 1 :
using System;
using System.Collections;
using UnityEngine;
using GoogleMobileAds.Api;
public class RewardedScriptRow : MonoBehaviour
{
private RewardBasedVideoAd rewardBasedVideo;
public AudioClip GiftSound;
public static RewardedScriptRow Instance;
// Use this for initialization
void Start()
{
Instance = this;
DontDestroyOnLoad(this);
RequestRewardBasedVideo();
rewardBasedVideo.OnAdFailedToLoad += HandleRewardBasedVideoClosed;
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
//Called after 10 questions
public void LaunchAd()
{
StartCoroutine("Load");
}
private void RequestRewardBasedVideo()
{
string adUnitId = "";
#if UNITY_ANDROID
adUnitId = "ca-app-pub-0000000/0000000000";
#elif UNITY_IOS
adUnitId = "ca-app-pub-00000/00000000";
#else
adUnitId = "unexpected_platform";
#endif
// Get singleton reward based video ad reference.
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
this.rewardBasedVideo.LoadAd(request, adUnitId);
}
//EVENT
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
GetComponent<AudioSource>().PlayOneShot(GiftSound, 1.0F);
RequestRewardBasedVideo();
}
public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
{
GetComponent<AudioSource>().PlayOneShot(GiftSound, 1.0F);
RequestRewardBasedVideo();
}
IEnumerator Load()
{
while (!rewardBasedVideo.IsLoaded())
yield return new WaitForEndOfFrame();
yield return new WaitForSeconds(0.0f);
rewardBasedVideo.Show();
yield break;
}
}
And this how the game work with the scenes :
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
First of all:
It seems very unwise/ illogical to call the RequestInterstial method in your event. Because by doing so, you are creating multiple subscriptions to the same events that you are already subscribed to! This can lead to very undesired/ unwanted behaviour as well as leading to Stackoverflow exceptions
It is unclear to me why you would even call RequestInterstial when the event fires. It seems to me that you would want to load a new video after the first one has been shown. Refactor your method so that you do not add the subscription events.
Move the subscription events and initialization code to your Start or Awake method.
Also you are not requesting an interstial, but a rewardbasedvideo. I'd suggest renaming to keep the code logical.
Public static RewardedScriptRow Instance;
void Start()
{
Instance = this;
DontDestroyOnLoad(this);
RequestRewardBasedVideo();
// Get singleton reward based video ad reference.
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
rewardBasedVideo.OnAdFailedToLoad += HandleRewardBasedVideoClosed;
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
private void RequestRewardBasedVideo()
{
#if UNITY_ANDROID
string appId = "ca-app-pub-3940256099942544~3347511713";
#elif UNITY_IPHONE
string appId = "ca-app-pub-3940256099942544~1458002511";
#else
string appId = "unexpected_platform";
#endif
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the rewarded video ad with the request.
this.rewardBasedVideo.LoadAd(request, adUnitId);
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
GetComponent<AudioSource>().PlayOneShot(GiftSound, 1.0F);
RequestRewardBasedVideo();
}
Other than that, it should work. If you are still not getting the desirable result, try setting breakpoints while debugging and/ or use Debug.Log() inside the subscribed methods to see what's happening.
Edit: Also, if it is happening because of reloading scenes, you could try adding DontDestroyOnLoad(this); to prevent the "AdObject" from getting destroyed. I'd suggest creating this script in your very first scene and removing it from all others (to prevent duplicates).
You can then even apply the singleton pattern so you can easily access the script from within other classes.
Example:
StartCoroutine(RewardedScriptRow.Instance.LaunchAd());

Unity Admob Interstitial Ads Not Showing

I know this question has been asked several times but i got stuck even though i have implemented and tried all the solutions. I follow this tutorial for interstitial ads showing:
https://developers.google.com/admob/unity/interstitial
My main goal is to show ad whenever user taps on "Restart" button for the game.
Here is my main ad manager class (which is linked with an game object):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
public class AdManager : MonoBehaviour {
public string interstitial_id;
public string app_id;
public InterstitialAd interstitial;
// Use this for initialization
void Start () {
//MobileAds.Initialize(app_id);
DontDestroyOnLoad(this);
Prepare_Video();
Debug.Log("Admob ilklendirildi: " + interstitial.ToString());
}
public void Show_Video()
{
Debug.Log("Reklam hazırlık durumu: " + interstitial.IsLoaded());
if (interstitial.IsLoaded()) {
Debug.Log("Reklam hazır, gösterilecek");
interstitial.Show();
}
else
{
Prepare_Video();
interstitial.Show();
}
}
public void Destroy_Video()
{
if(interstitial != null)
{
interstitial.Destroy();
}
}
public void Prepare_Video()
{
interstitial = new InterstitialAd(interstitial_id);
AdRequest request = new AdRequest.Builder().Build();
interstitial.LoadAd(request);
}
}
I call the show method in restart action:
public void RestartScene()
{
GameStatusText.gameObject.SetActive(false);
RestartButton.gameObject.SetActive(false);
MeterText.gameObject.SetActive(false);
MeterTextTop.text = "";
Time.timeScale = 1;
TimeController.TimeLeft = 50f;
FindObjectOfType<AdManager>().Show_Video();
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
you need Initialize admob first
Check what's going on with the scene that AdManager is assigned to, and if there is any changes to the scene, and do you have Google Ads unity asset installed in your game?
I have reinstalled the admob plugin and followed the instructions from the beginning. It worked. It seems like my plugin package was damaged and some files were missing.

showing admob interstitial every x play unity

I am trying to make my interstitial admob ad appear when a user enters the map for the third time.
My code is:
using UnityEngine;
using System.Collections;
using GoogleMobileAds;
using GoogleMobileAds.Api;
public class interstitial_ad : MonoBehaviour {
private InterstitialAd interstitial;
void Start()
{
interstitial = new InterstitialAd ("ca-app-pub-xxx");
interstitial.LoadAd (new AdRequest.Builder ().Build ());
}
void Update()
{
if (interstitial.IsLoaded())
{
interstitial.Show();
}
}
}
It shows the ad every time I enter the map, so I tried to add:
playCount++;
if (playCount % 3 == 0) {
but that did not work for me, probably because of the void Update() part. Do you have any ideas/hints how to make it work?