Banner Ads shows after reload scene - c#

In my project, the banner opens after the scene is reloaded, everything seems to be in order in the editor.
Everything works fine in the editor, I checked it, but it’s only worth building the project on Android, it doesn’t work there normally. It will appear only after the scene is reloaded, and then not immediately with a delay of 2-3 seconds.
My code:
using UnityEngine;
using System.Collections;
using UnityEngine.Advertisements;
public class BannerAd : MonoBehaviour
{
[SerializeField] BannerPosition _bannerPosition;
[SerializeField] private string _androidAdUnitId = "Banner_Android";
[SerializeField] private string _iOSAdUnitId = "Banner_iOS";
private string _adUnitId;
private void Awake()
{
_adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOSAdUnitId
: _androidAdUnitId;
}
private void Start()
{
Advertisement.Banner.SetPosition(_bannerPosition);
LoadBanner();
}
private IEnumerator LoadAdBanner()
{
yield return new WaitForSeconds(1f);
LoadBanner();
}
public void LoadBanner()
{
BannerLoadOptions options = new BannerLoadOptions
{
loadCallback = OnBannerLoaded,
errorCallback = OnBannerError
};
Advertisement.Banner.Load(_adUnitId, options);
}
private void OnBannerLoaded()
{
Debug.Log("Banner loaded");
ShowBannerAd();
}
private void OnBannerError(string message)
{
Debug.Log($"Banner Error: {message}");
}
public void ShowBannerAd()
{
BannerOptions options = new BannerOptions
{
clickCallback = OnBannerClicked,
hideCallback = OnBannerHidden,
showCallback = OnBannerShown
};
Advertisement.Banner.Show(_adUnitId, options);
}
public void HideBannerAd()
{
Advertisement.Banner.Hide();
}
private void OnBannerClicked() { }
private void OnBannerShown() { }
private void OnBannerHidden() { }
}

It might be the ad is still not initialized when you call LoadBanner so it doesn't work at first. The best is to call LoadBanner when Initialization is complete. Set _testMode to true or false based on your need.
public class BannerAd : MonoBehaviour, IUnityAdsInitializationListener
{
[SerializeField] bool _testMode = true;
private string _adUnitId;
void Awake()
{
InitializeAds();
}
public void InitializeAds()
{
_adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOSGameId
: _androidGameId;
Advertisement.Initialize(_adUnitId, _testMode, this);
}
public void OnInitializationComplete()
{
LoadBanner();
}
//rest of the code
}
}

Related

Rewarded Ads give multiple rewards instead of one (Video in the description)

I used the code from Unity and the rewards are multiples... first 1 then 2 then 3 and increasing... i tried deleting some code, but keep doing the same, then this happened.
I searched online and i couldn't find anything that explains clicking the rewarded ads button more than once.
Everything (apparently) is working fine only if i don't assing a button and leave the "SerializeField" empty, because if i remove the button, goes back to give more rewards... can somebody check this and tell me what's going on? i add the code Here
using UnityEngine;
using UnityEngine.Advertisements;
using UnityEngine.UI;
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener, IUnityAdsLoadListener, IUnityAdsShowListener
{
[SerializeField] string _androidGameId = "4634758";
[SerializeField] string _iOSGameId = "4634759";
[SerializeField] bool _testMode = false;
private string _gameId;
[SerializeField] Button _showAdButton;
[SerializeField] string rewardAndroidAdUnitId = "Rewarded_Android";
[SerializeField] string rewardiOSAdUnitId = "Rewarded_iOS";
string rewardAdUnitId = null; // This will remain null for unsupported platforms
void Awake()
{
_gameId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOSGameId
: _androidGameId;
rewardAdUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? rewardiOSAdUnitId
: rewardAndroidAdUnitId;
Advertisement.Initialize(_gameId, _testMode, this);
rewardAdUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? rewardiOSAdUnitId
: rewardAndroidAdUnitId;
}
public void OnInitializationComplete()
{
Debug.Log("Unity Ads initialization complete.");
LoadRewardedAd();
}
public void OnInitializationFailed(UnityAdsInitializationError error, string message)
{
Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
}
#region REWARDED ADS
public void LoadRewardedAd()
{
Debug.Log("Loading Ad: " + rewardAdUnitId);
Advertisement.Load(rewardAdUnitId, this);
}
public void ShowRewardedAd()
{
Advertisement.Show(rewardAdUnitId, this);
}
#endregion
public void OnUnityAdsAdLoaded(string adUnitId)
{
if (adUnitId.Equals(rewardAdUnitId))
{
// Configure the button to call the ShowAd() method when clicked:
//_showAdButton.onClick.AddListener(ShowRewardedAd);
// Enable the button for users to click:
//_showAdButton.interactable = true;
Debug.Log("RewardedAds Loaded");
}
}
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
{
if (adUnitId.Equals(rewardAdUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
{
Debug.Log("Unity Ads Rewarded Ad Completed");
// Grant a reward.
_showAdButton.onClick.RemoveAllListeners(); //with this line of code the problem is solved but shows the NullReference.
// Load another ad:
Advertisement.Load(rewardAdUnitId, this);
}
}
public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
{
if (adUnitId.Equals(rewardAdUnitId))
{
Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
}
}
public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
{
if (adUnitId.Equals(rewardAdUnitId))
{
Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
}
}
public void OnUnityAdsShowStart(string adUnitId) { }
public void OnUnityAdsShowClick(string adUnitId) { }
void OnDestroy()
{
//with or without it doesn't change, it works only when the game is closed, and when reopen is working the same
//_showAdButton.onClick.RemoveAllListeners();
}
}
SOLVED!!
So, basically the script from Unity somehow has an unknown error, i couldn't explain myself how or from where... so the solution i fould was to add a bool in this case showAd = false and implemented it inside the showAd and the OnUnityAdsShowComplete functions, fortunatelly that was enough to solve the issue, now I can put the script in the button or in an AdManager and call the funtion from the button in the section OnClick() either way now is not showing neither error neither multiples with the rewards.
Hope it will be usefull for someone else.
using UnityEngine;
using UnityEngine.Advertisements;
using UnityEngine.UI;
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener, IUnityAdsLoadListener, IUnityAdsShowListener
{
[SerializeField] string _androidGameId = "4634758";
[SerializeField] string _iOSGameId = "4634759";
[SerializeField] bool _testMode = true;
private string _gameId;
[SerializeField] Button _showAdButton; //You can remove this if want to add the function manually from OnClick()
[SerializeField] string _androidAdUnitId = "Rewarded_Android";
[SerializeField] string _iOSAdUnitId = "Rewarded_iOS";
string _adUnitId = null; // This will remain null for unsupported platforms
private bool showAd = false;
void Awake()
{
InitializeAds();
Debug.Log("Awake");
_adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOSAdUnitId
: _androidAdUnitId;
Debug.Log("the _adUnitId is: " + _adUnitId);
}
public void InitializeAds()
{
_gameId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOSGameId
: _androidGameId;
Advertisement.Initialize(_gameId, _testMode, this);
}
public void OnInitializationComplete()
{
Debug.Log("Unity Ads initialization complete.");
LoadAd();
}
public void OnInitializationFailed(UnityAdsInitializationError error, string message)
{
Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
}
public void LoadAd()
{
// IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled on top of the 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); //You can remove this if want to add the function manually from OnClick()
// Enable the button for users to click:
_showAdButton.interactable = true; //You can remove this if want to add the function manually from OnClick()
}
}
// Implement a method to execute when the user clicks the button:
public void ShowAd()
{
if (showAd == false)
{
Debug.Log("Showing Ad");
// Disable the button:
_showAdButton.interactable = false; //You can remove this if want to add the function manually from OnClick()
// Then show the ad:
Advertisement.Show(_adUnitId, this);
_showAdButton.onClick.RemoveAllListeners(); //You can remove this if want to add the function manually from OnClick()
Debug.Log("All Listeners Removed");
showAd = true;
}
}
// Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
{
if (showAd == true)
{
if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
{
Debug.Log("Unity Ads Rewarded Ad Completed");
// Grant a reward.
// Load another ad:
Advertisement.Load(_adUnitId, this);
showAd = false;
}
}
}
public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
{
Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
// Use the error details to determine whether to try to load another ad.
}
public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
{
Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
// Use the error details to determine whether to try to load another ad.
}
public void OnUnityAdsShowStart(string adUnitId) { }
public void OnUnityAdsShowClick(string adUnitId) { }
}

Wait for GetComponent() to load

When calling GetComponent() just after my program starts up, I find that the method sometimes does not return a component quickly enough to prevent a null reference exception when code later tries to access the component member variable. My question is - is there a way to wait for GetComponent to finish finding what it needs to? I know can wait using coroutines, but is there another way to do this with some kind of lambda callback or event?
public class GameManager : MonoBehaviour
{
public bool AutosaveEnabled = true;
public static GameManager Instance;
[HideInInspector] public InputManager InputManager;
[HideInInspector] public UIManager UIManager;
...
private void Awake()
{
Setup();
}
public void Setup()
{
if (Instance == null)
{
Instance = this;
}
else
{
throw new Exception();
}
UIManager = GetComponent<UIManager>();
...
UIManager.Setup();
...
}
public class UIManager : StateMachine, IUIManager
{
public static UIManager Instance;
public ITitleMenu TitleMenu;
public void Setup()
{
if (Instance == null)
{
Instance = this;
}
else
{
throw new Exception();
}
TitleMenu = GetComponentInChildren<ITitleMenu>();
}
private void SetupScene()
{
UIManager.Instance.ChangeState<TitleMenuState>();
}
...
}
public interface ITitleMenu : IMenu
{
void ExitGame();
void LoadTitleMenuScene();
void OnNewGameClick();
}
public interface IMenu
{
public void Setup(IUIManager uiManager);
public void SetActive(bool toggle);
int selectedIndex { get; set; }
int previouslySelectedIndex { get; set; }
TextMeshProUGUI[] Options { get; set; }
void OnControllerMoveDown();
void OnControllerMoveUp();
void OnControllerConfirm();
}
public class TitleMenu : MenuBase, ITitleMenu
{
private enum MenuElements { Continue, NewGame, Controls, VideoSettings, AudioSettings, ExitGame };
public void Setup(IUIManager uiManager)
{
this.uiManager = uiManager;
DataManager.Instance.SaveFileMetadata = GameManager.Instance.SaveFileManager.GetSaveFileMetadata();
if (DataManager.Instance.SaveFileMetadata.Count > 0)
{
Options[(int)MenuElements.Continue].transform.parent.gameObject.SetActive(true);
selectedIndex = (int)MenuElements.Continue;
}
else
{
Options[(int)MenuElements.Continue].transform.parent.gameObject.SetActive(false);
selectedIndex = (int)MenuElements.NewGame;
}
previouslySelectedIndex = selectedIndex;
}
...
}
public class StateMachine : MonoBehaviour, IStateMachine
{
public virtual State CurrentState
{
get
{
return _currentState;
}
set
{
if (_currentState == value)
{
return;
}
if (_currentState != null)
{
_currentState.Exit();
}
_currentState = value;
if (_currentState != null)
{
_currentState.Enter();
}
}
}
protected State _currentState;
public virtual T GetState<T>() where T : State
{
T target = GetComponent<T>();
if (target == null)
{
target = gameObject.AddComponent<T>();
target.Initialize();
}
return target;
}
}
...
public class TitleMenuState : UIState
{
protected override void OnMove(object sender, InfoEventArgs<Vector2> e)
{
if (e.info.y == 1)
{
owner.TitleMenu.OnControllerMoveUp();
}
else if (e.info.y == -1)
{
owner.TitleMenu.OnControllerMoveDown();
}
}
protected override void OnInteract(object sender, EventArgs e)
{
owner.TitleMenu.OnControllerConfirm();
}
public override void Enter()
{
owner.TitleMenu.SetActive(true);
owner.TitleMenu.Setup(owner);
EventManager.UIMoveEvent += OnMove;
EventManager.UISubmitEvent += OnInteract;
}
public override void Exit()
{
UIManager.Instance.TitleMenu.SetActive(false);
EventManager.UIMoveEvent -= OnMove;
EventManager.UISubmitEvent -= OnInteract;
}
}
public abstract class State : MonoBehaviour
{
public virtual void Enter()
{
}
public virtual void Exit()
{
}
public virtual void Initialize()
{
}
}
public abstract class UIState : State
{
protected UIManager owner;
public override void Initialize()
{
owner = UIManager.Instance;
}
protected virtual void OnInteract(object sender, EventArgs e)
{
}
protected virtual void OnCancel(object sender, EventArgs args)
{
}
public override void Enter()
{
}
public override void Exit()
{
}
protected virtual void OnMove(object sender, InfoEventArgs<Vector2> e)
{
}
public virtual bool IsStateOfType(UIStates state)
{
return false;
}
}
Right now the game crashes in TitleMenuState.Enter() where I'm calling owner.TitleMenu.SetActive() because TitleMenu is null.
Hierarchy:
At the time TitleMenu = GetComponentInChildren<ITitleMenu>(); is run in the UIManager component of the GameManager gameobject, the child gameobject TitleMenu is inactive, and that child is what has the ITitleMenu on it. And, from the documentation on GetComponentInChildren (emphasis mine):
Returns the component of Type type in the GameObject or any of its children using depth first search.
A component is returned only if it is found on an active GameObject.
So that will return null. This has nothing to do with failing to return "quickly enough".
A very simple workaround is to use GetComponentsInChildren, which has an optional includeInactive parameter that will allow for searching inactive objects. Using GetComponentsInChildren, with includeInactive as true should have the desired result, only needing to index the first element (since it returns an array):
public class UIManager : StateMachine, IUIManager
{
public static UIManager Instance;
public ITitleMenu TitleMenu;
public void Setup()
{
if (Instance == null)
{
Instance = this;
}
else
{
throw new Exception();
}
TitleMenu = GetComponentsInChildren<ITitleMenu>(true)[0];
}
You should call GetComponent() before using the component. You could also check out Script Execution order menu (Edit - Project Settings - Script Execution order)

Rewarded video ads events not firing in Unity and Admob

I am using Unity 2019.2.8f1 and I am preparing to publish my first game on Google Play Store. Unfortunately the reward is not being given to the user after watching a rewarded ad. The user should get an extra life whenever he/she watches a rewarded ad.
Here is my Ad Manager script. I am using dummy ids for testing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using System;
public class AdManager : MonoBehaviour
{
public static AdManager instance;
private string AppId = "ca-app-pub-3940256099942544~3347511713";
private BannerView banner;
private string bannerID = "ca-app-pub-3940256099942544/6300978111";
private InterstitialAd videoAD;
private string videoID = "ca-app-pub-3940256099942544/1033173712";
private int showing, video;
private RewardBasedVideoAd rewardedAds;
private string rewardedID = "ca-app-pub-3940256099942544/5224354917";
public bool RewardTaken;
public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
{
Debug.Log("HandleRewardBasedVideoClosed event received");
RequestRewardedAD();
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
UIManager.variable.RewardPanel.SetActive(true);
UIManager.variable.gameOver.SetActive(false);
}
private void Awake()
{
rewardedAds = RewardBasedVideoAd.Instance;
showing = PlayerPrefs.GetInt("show");
video = PlayerPrefs.GetInt("video");
MobileAds.Initialize(AppId);
RequestvideoAD();
if (instance == null)
{
instance = this;
}
else
{
Destroy(this);
}
}
private void Start()
{
RewardTaken = false;
if (video == 1)
{
ShowvideoAD();
}
if (showing == 1)
{
requestBanner();
}
RequestRewardedAD();
// Called when the user should be rewarded for watching a video.
rewardedAds.OnAdRewarded += HandleRewardBasedVideoRewarded;
// Called when the ad is closed.
rewardedAds.OnAdClosed += HandleRewardBasedVideoClosed;
}
public void requestBanner()
{
banner = new BannerView(bannerID, AdSize.Banner, AdPosition.Bottom);
AdRequest request = new AdRequest.Builder().Build();
banner.LoadAd(request);
banner.Show();
}
public void RequestvideoAD()
{
videoAD = new InterstitialAd(videoID);
AdRequest request = new AdRequest.Builder().Build();
videoAD.LoadAd(request);
}
public void ShowvideoAD()
{
if (videoAD.IsLoaded())
{
videoAD.Show();
}
else
{
Debug.Log("FullscreenADNotLoaded");
}
}
public void RequestRewardedAD()
{
AdRequest request = new AdRequest.Builder().Build();
rewardedAds.LoadAd(request,rewardedID);
}
public void ShowRewardedAD()
{
if(rewardedAds.IsLoaded())
{
rewardedAds.Show();
Debug.Log("Ads Are Working");
}
else
{
Debug.Log("Rewarded Ads not laded properly");
}
}
public void HideAD()
{
banner.Hide();
}
}
Even though the console was not showing any message that I wanted to show as a part of the test. After trying several times, I decided to remove the debug text.
It looks like you are attaching Callbacks to a different ad object and you are loading ads from a different object.
Try using rewardedAds
to Load Ad
public void RequestvideoAD()
{
AdRequest request = new AdRequest.Builder().Build();
rewardedAds.LoadAd(request);
}

How to properly reward player with Admob rewarded video in Unity?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using UnityEngine.UI;
public class AdManager : MonoBehaviour {
RewardBasedVideoAd rewardBasedVideo;
static InterstitialAd interstitial;
string VideoID = "ca-app-pub-3888784411212422/2850896103";
string adUnitId = "ca-app-pub-3888784411212422/4158795262";
public static AdManager Instance;
void Start ()
{
Instance = this;
DontDestroyOnLoad(gameObject);
RequestRewardBasedVideo();
RequestInterstitial();
}
public void RequestRewardBasedVideo()
{
rewardBasedVideo = RewardBasedVideoAd.Instance;
rewardBasedVideo.LoadAd(new AdRequest.Builder().Build(), adUnitId);
}
public void RequestInterstitial()
{
interstitial = new InterstitialAd(VideoID);
interstitial.LoadAd(new AdRequest.Builder().Build());
}
public void ShowAd()
{
if(rewardBasedVideo.IsLoaded())
{
rewardBasedVideo.Show();
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
}
public static void ShowInter()
{
showInterstitial(interstitial);
}
private void showAdd(RewardBasedVideoAd r)
{
if (r.IsLoaded())
{
//Subscribe to Ad event
r.Show();
r.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
PlayerPrefs.SetInt("coin", PlayerPrefs.GetInt("coin") + 200);
GameObject.FindGameObjectWithTag("Coin").GetComponent<Text>().text = PlayerPrefs.GetInt("coin").ToString();
GameObject.FindGameObjectWithTag("Double").GetComponent<Button>().interactable = false;
Debug.Log("Pref: " + PlayerPrefs.GetInt("coin"));
}
static void showInterstitial(InterstitialAd i)
{
if (i.IsLoaded())
{
i.Show();
}
}
}
I am rewarding players with 200 coins, but somehow every time i get reward increased by 200. First time when player get rewarded he gets 200, next time he gets 400, next time 600 etc. I have tried to change code in many ways but no positive result.
Method that is called upon button click is ShowAd(). Every time when panel with button thats calls the method is shown i call RequestRewardBasedVideo().
adding and creating new objects is the answer,
for example the Void would have something like that
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
int CoinOld = PlayerPrefs.GetInt("coin");
CoinOld += 200;
PlayerPrefs.SetInt("coin", CoinOld);
GameObject.FindGameObjectWithTag("Coin").GetComponent<Text>().text = PlayerPrefs.GetInt("coin").ToString();
GameObject.FindGameObjectWithTag("Double").GetComponent<Button>().interactable = false;
Debug.Log("Pref: " + PlayerPrefs.GetInt("coin"));
}

Chartboost ads not showing in Unity 3D Game

I have a simple platformer game in which I'm using chartboost and unity ads t show ads and I it was working fine during the test mode but ever since I deployed to production and disabled the test mode in both chartboost and unity ads I noticed that my interstitial ads and videos don't load or show except once in a blue moon that too of a same game and then it start failing again.
I also noticed that my ads impression are quite low on the chartboost and Unity. Can you please tell me if I code for it correctly? I used the chartboost example an built my ad controller through it, oh and I'm using caching for ads and unless ad isn't cached already I won't show it.
Here's the code:
using UnityEngine;
using System.Collections;
using UnityEngine.Advertisements;
using ChartboostSDK;
using System;
public class AdsController : MonoBehaviour
{
public static AdsController instance;
// app id for unity apps
private const string _appId = "someID";
public bool canShowChartBoostInterstitial;
public bool canShowChartBoostVideo;
private void Awake()
{
MakeSingleton();
if (!canShowChartBoostInterstitial)
{
LoadChartBoostInterstitialAds();
}
if (!canShowChartBoostVideo)
{
LoadChartBoostVideoAds();
}
LoadUnityAds();
}
private void MakeSingleton()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
private void OnLevelWasLoaded()
{
if (Application.loadedLevelName == "LevelMenu")
{
if (GameController.instance.canShowAds)
{
if (canShowChartBoostInterstitial)
{
ShowChartBoostInterstitial();
}
else
{
LoadChartBoostInterstitialAds();
}
}
}
}
private void OnEnable()
{
Chartboost.didCompleteRewardedVideo += VideoCompleted;
Chartboost.didCacheInterstitial += DidCacheInterstitial;
Chartboost.didDismissInterstitial += DidDismissInterstitial;
Chartboost.didCloseInterstitial += DidCloseInterstitial;
Chartboost.didCacheRewardedVideo += DidCacheVideo;
Chartboost.didFailToLoadInterstitial += FailedToLoadInterstitial;
Chartboost.didFailToLoadRewardedVideo += FailedToLoadVideo;
}
private void OnDisable()
{
Chartboost.didCompleteRewardedVideo -= VideoCompleted;
Chartboost.didCacheInterstitial -= DidCacheInterstitial;
Chartboost.didDismissInterstitial -= DidDismissInterstitial;
Chartboost.didCloseInterstitial -= DidCloseInterstitial;
Chartboost.didCacheRewardedVideo -= DidCacheVideo;
Chartboost.didFailToLoadInterstitial -= FailedToLoadInterstitial;
Chartboost.didFailToLoadRewardedVideo -= FailedToLoadVideo;
}
public void VideoCompleted(CBLocation location, int reward)
{
canShowChartBoostVideo = false;
if (RewardController.instance != null)
{
RewardController.instance.VideoWatchedGiveUserAReward();
}
LoadChartBoostVideoAds();
}
public void DidCacheInterstitial(CBLocation location)
{
canShowChartBoostInterstitial = true;
}
public void DidDismissInterstitial(CBLocation location)
{
canShowChartBoostInterstitial = false;
LoadChartBoostVideoAds();
LoadChartBoostInterstitialAds();
}
public void DidCloseInterstitial(CBLocation location)
{
canShowChartBoostInterstitial = false;
LoadChartBoostVideoAds();
LoadChartBoostInterstitialAds();
}
public void DidCacheVideo(CBLocation location)
{
canShowChartBoostVideo = true;
}
private void FailedToLoadInterstitial(CBLocation location, CBImpressionError error)
{
canShowChartBoostInterstitial = false;
LoadChartBoostInterstitialAds();
}
private void FailedToLoadVideo(CBLocation location, CBImpressionError error)
{
canShowChartBoostVideo = false;
if (ShopMenuController.instance != null)
{
ShopMenuController.instance.FailedToLoadTheVideo();
}
LoadChartBoostVideoAds();
}
public void LoadChartBoostVideoAds()
{
Chartboost.cacheRewardedVideo(CBLocation.Default);
}
public void LoadChartBoostInterstitialAds()
{
Chartboost.cacheInterstitial(CBLocation.Default);
}
public void ShowChartBoostInterstitial()
{
if (canShowChartBoostInterstitial)
{
Chartboost.showInterstitial(CBLocation.Default);
}
else
{
LoadChartBoostInterstitialAds();
}
}
public void ShowChartBoostVideo()
{
if (canShowChartBoostVideo)
{
Chartboost.showRewardedVideo(CBLocation.Default);
}
else
{
LoadChartBoostVideoAds();
}
}
public void LoadUnityAds()
{
if (Advertisement.isSupported)
{
Advertisement.Initialize(_appId, false);
}
}
public void ShowUnityAds()
{
if (Advertisement.IsReady())
{
Advertisement.Show(null, new ShowOptions()
{
resultCallback = result =>
{
switch (result)
{
case ShowResult.Finished:
GameController.instance.RewardPlayerWithSomething();
LoadUnityAds();
break;
case ShowResult.Failed:
GameController.instance.VideoNotLoadedOrUserSkippedTheVideo("Failed to load the video. Please try again.");
LoadUnityAds();
break;
case ShowResult.Skipped:
GameController.instance.VideoNotLoadedOrUserSkippedTheVideo("Video skipped.");
LoadUnityAds();
break;
}
}
});
}
else
{
GameController.instance.VideoNotLoadedOrUserSkippedTheVideo("Failed to load the video. Please try again.");
LoadUnityAds();
}
}
}
Run cache after every time you show an interstitial.
like this :
Chartboost.showInterstitial(CBLocation.Default);
Chartboost.cacheInterstitial(CBLocation.Default);
That way you will replenish the cache every time you show an ad.
Remember to cache as soon as its initialized as well.

Categories

Resources