Not working leaderboard Google Play Service - c#

added a leaderboard to the Google Play Service. Resources are added, authorization is working, adding a record is working. But when use ShowLeaderboardUI() only shows the name of the highscore table, but there are no highscores. Help pls ;(
CODE Ads Init:
public class AdsInitialize : MonoBehaviour
{
public static AdsInitialize instance = null;
private string LEADER_BOARD = "******";
public Text _text;
private void Awake()
{
if (instance == null)
{
instance = this;
MobileAds.Initialize(initStatus => { });
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate();
Social.localUser.Authenticate(success =>
{
if (success)
{
_text.text = "Auth working";
}
else
{
_text.text = "Auth not working";
}
});
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
public void ShowLeaderBoard()
{
//Social.ShowLeaderboardUI();
PlayGamesPlatform.Instance.ShowLeaderboardUI(LEADER_BOARD);
}
}
Write highscores:
Social.ReportScore(_time, AdsInitialize.instance.LEADER_BOARD, (bool success) => {
if (success)
{
_text.text = "ReportScore working";
}
else
{
_text.text = "ReportScore not working";
}
});
Show leaderboard in menu (this method is hanging on button):
public void ShowLeaderBoard()
{
AdsInitialize.instance.ShowLeaderBoard();
}

You need update your Google Play Games at phone

Related

I am getting 6 errors, it looks like all of them are in IEnumerators [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
Here are the errors.
I am creating a firebase login and sign up unity project.
I have commented some of the lines because I havent programmed it yet. I am following this tutorial : https://www.youtube.com/watch?v=9-ZS7-I_CfQ
I have 2 scripts, firebaseManager and authUI manager.
Here is my firebaseManager script:
using UnityEngine;
using System.Collections;
using Firebase;
using Firebase.Auth;
using TMPro;
public class FirebaseManager : MonoBehaviour
{
public static FirebaseManager instance;
[Header("Firebase")]
public FirebaseAuth auth;
public FirebaseUser user;
[Space(5f)]
[Header("Login References")]
[SerializeField]
private TMP_InputField loginEmail;
[SerializeField]
private TMP_InputField loginPassword;
[SerializeField]
private TMP_Text loginOutputText;
[Space(5f)]
[Header("Register References")]
[SerializeField]
private TMP_InputField registerUsername;
[SerializeField]
private TMP_InputField registerEmail;
[SerializeField]
private TMP_InputField registerPassword;
[SerializeField]
private TMP_InputField registerConfirmPassword;
[SerializeField]
private TMP_Text registerOutputText;
private void Awake()
{
DontDestroyOnLoad(gameObject);
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(instance.gameObject);
instance = this;
}
}
private void Start()
{
StartCoroutine(CheckAndFixDependancies());
}
private IEnumerator CheckAndFixDependancies()
{
var checkAndFixDependanciesTask = FirebaseApp.CheckAndFixDependenciesAsync();
yield return new WaitUntil(predicate: () => checkAndFixDependanciesTask.IsCompleted);
var dependancyResult = checkAndFixDependanciesTask.Result;
if (dependancyResult == DependencyStatus.Available)
{
InitializeFirebase();
}
else
{
Debug.LogError($"Could not resolve all firebase dependancies: {dependancyResult}");
}
}
private void InitializeFirebase()
{
auth = FirebaseAuth.DefaultInstance;
StartCoroutine(CheckAutoLogin());
auth.StateChanged += AuthStateChanged;
AuthStateChanged(this, null);
}
private IEnumerator CheckAutoLogin()
{
yield return new WaitForEndOfFrame();
if (user != null)
{
var reloadUserTask = user.ReloadAsync();
yield return new WaitUntil(predicate: () => reloadUserTask.IsCompleted);
AutoLogin();
}
else
{
AuthUIManager.instance.LoginScreen();
}
}
private void AutoLogin()
{
if (user != null)
{
if (user.IsEmailVerified)
{
GameManager.instance.ChangeScene(1);
}
else
{
StartCoroutine(SendVerificationEmail());
}
}
else
{
AuthUIManager.instance.LoginScreen();
}
}
private void AuthStateChanged(object sender, System.EventArgs eventArgs)
{
if (auth.CurrentUser != user)
{
bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null;
if (!signedIn && user != null)
{
Debug.Log("Signed Out");
// Write signed out user code here
}
user = auth.CurrentUser;
if (signedIn)
{
Debug.Log($"Signed In: {user.DisplayName}");
}
}
}
public void ClearOutputs()
{
loginOutputText.text = "";
registerOutputText.text = "";
}
public void LoginButton()
{
StartCoroutine(LoginLogic(loginEmail.text, loginPassword.text));
}
public void RegisterButton()
{
StartCoroutine(RegisterLogic(registerUsername.text, registerEmail.text, registerPassword.text, registerConfirmPassword.text));
}
private IEnumerator LoginLogic(string _email, string _password)
{
Credential credential = EmailAuthProvider.GetCredential(_email, _password);
var loginTask = auth.SignInWithCredentialAsync(credential);
yield return new WaitUntil(predicate: () => loginTask.IsCompleted);
if (loginTask.Exception != null)
{
FirebaseException firebaseException = (FirebaseException)loginTask.Exception.GetBaseException();
AuthError error = (AuthError)firebaseException.ErrorCode;
string output = "Unknown Error, Please Try Again";
switch (error)
{
case AuthError.MissingEmail:
output = "Please Enter Your Email";
break;
case AuthError.MissingPassword:
output = "Please Enter Your Password";
break;
case AuthError.InvalidEmail:
output = "Invalid Email";
break;
case AuthError.WrongPassword:
output = "Incorrect Password";
break;
case AuthError.UserNotFound:
output = "Account Does Not Exist";
break;
}
loginOutputText.text = output;
}
else
{
if (user.IsEmailVerified)
{
yield return new WaitForSeconds(1f);
GameManager.instance.ChangeScene(1);
}
else
{
StartCoroutine(SendVerificationEmail());
}
}
}
private IEnumerator RegisterLogic(string _username, string _email, string _password, string _confirmPassword)
{
if (_username == "")
{
registerOutputText.text = "Please Enter A Username";
}
else if (_password != _confirmPassword)
{
registerOutputText.text = "Passwords Do Not Match!";
}
// else if (_username.ToLower() == "bad word")
// {
// registerOutputText.text = "That Username Is Innapropriate";
// }
else
{
var registerTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);
yield return new WaitUntil(predicate: () => registerTask.IsCompleted);
if (registerTask.Exception != null)
{
FirebaseException firebaseException = (FirebaseException)registerTask.Exception.GetBaseException();
AuthError error = (AuthError)firebaseException.ErrorCode;
string output = "Unknown Error, Please Try Again";
switch (error)
{
case AuthError.InvalidEmail:
output = "Invalid Email";
break;
case AuthError.EmailAlreadyInUse:
output = "Email Is Already In Use";
break;
case AuthError.WeakPassword:
output = "Weak Password. Please include capital letters, numbers and special symbols.";
break;
case AuthError.MissingEmail:
output = "Please Enter Your Email";
break;
case AuthError.MissingPassword:
output = "Please Enter Your Password";
break;
}
registerOutputText.text = output;
}
else
{
UserProfile profile = new UserProfile
{
DisplayName = _username,
PhotoUrl = new System.Uri("https://t4.ftcdn.net/jpg/02/29/75/83/360_F_229758328_7x8jwCwjtBMmC6rgFzLFhZoEpLobB6L8.jpg");
};
var defaultUserTask = user.UpdateUserProfileAsync(profile);
yield return new WaitUntil(predicate: () => defaultUserTask.IsCompleted);
if (defaultUserTask.Exception != null)
{
user.DeleteAsync();
FirebaseException firebaseException = (FirebaseException)defaultUserTask.Exception.GetBaseException();
AuthError error = (AuthError)firebaseException.ErrorCode;
string output = "Unknown Error, Please Try Again";
switch (error)
{
case AuthError.Cancelled:
output = "Update User Cancelled";
break;
case AuthError.SessionExpired:
output = "Session Expired";
break;
}
registerOutputText.text = output;
}
else
{
Debug.Log($"Firebase User Created Successfuly: {user.DisplayName} ({user.UserId})");
StartCoroutine(SendVerificationEmail());
}
}
}
}
private IEnumerator SendVerificationEmail()
{
if (user != null)
{
var emailTask = user.SendEmailVerificationAsync();
yield return new WaitUntil(predicate: () => emailTask.IsCompleted);
if (emailTask.Exception != null)
{
FirebaseException firebaseException = (FirebaseException)emailTask.Exception.GetBaseException();
AuthError error = (AuthError)firebaseException.ErrorCode;
string output = "Unkown Error, Try Again!";
switch (error)
{
case AuthError.Cancelled:
output = "Verification Task Was Cancelled";
break;
case AuthError.InvalidRecipientEmail:
output = "Invalid Email";
break;
case AuthError.TooManyRequests:
output = "Too Many Requests";
break;
}
AuthUIManager.instance.AwaitVerification(false, user.Email, output);
}
else
{
AuthUIManager.instance.AwaitVerification(true, user.Email, null);
Debug.Log("Email Sent Successfully");
}
}
}
public void UpdateProfilePicture(string _newPfpURL)
{
StartCoroutine(UpdateProfilePictureLogic(_newPfpURL));
}
private IEnumerator UpdateProfilePictureLogic(string _newPfpURL)
{
if (user != null)
{
UserProfile profile = new UserProfile();
try
{
UserProfile _profile = new UserProfile
{
PhotoUrl = new System.Uri(_newPfpURL),
};
profile = _profile;
}
catch
{
// LobbyManager.instance.Output("Error Fetching Image, Make Sure Your Link Is Valid!");
yield break;
}
var pfpTask = user.UpdateProfileAsync(profile);
yield return new WaitUntil(predicate: () => pfpTask.IsCompleted);
if (pfpTask.Exception != null)
{
Debug.LogError($"Updating Profile Picture was unsuccessful: {pfpTask.Exception}");
}
else
{
LobbyManager.instance.ChangePfpSuccess();
Debug.Log("Profile Image Updated Successfully");
}
}
}
}
Here is my AuthUIManager script:
using TMPro;
using UnityEngine;
public class AuthUIManager : MonoBehaviour
{
public static AuthUIManager instance;
[Header("References")]
[SerializeField]
private GameObject checkingForAccountUI;
[SerializeField]
private GameObject loginUI;
[SerializeField]
private GameObject registerUI;
[SerializeField]
private GameObject verifyEmailUI;
[SerializeField]
private TMP_Text verifyEmailText;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
}
private void ClearUI()
{
loginUI.SetActive(false);
registerUI.SetActive(false);
verifyEmailUI.SetActive(false);
FirebaseManager.instance.ClearOutputs();
checkingForAccountUI.SetActive(false);
}
public void LoginScreen()
{
ClearUI();
loginUI.SetActive(true);
}
public void RegisterScreen()
{
ClearUI();
registerUI.SetActive(true);
}
public void AwaitVerification(bool _emailSent, string _email, string _output)
{
ClearUI();
verifyEmailUI.SetActive(true);
if (_emailSent)
{
verifyEmailText.text = $"Sent Email!\nPleaseVerify {_email}";
}
else
{
verifyEmailText.text = $"Email Not Sent: {_output}\nPlease Verify {_email}";
}
}
}
In your FirebaseManager script you've put a semicolon ; at the end of line 264 instead of a comma ,.
Additionally you've put a desperate closed curly bracket } at the end of the file, which is not necessary.
All other errors basically originate from these two problems.

PlayerStats.Valid not return true

I'm trying to get user status through google play services to make a daily rewards system for my game and I'm not getting the value back as true, my game connects to google play but I can not get the user's data. Here is the code snippet below
private string gameId = "3140248";
private bool testMode = true;
public List<Upgrades> upgrades = new List<Upgrades>();
public List<Area> areas = new List<Area>();
public Text Loading;
public GameObject ErrorGoogle;
public PlayerStats PlayerStats;
public void Start()
{
StartCoroutine("Connection");
}
IEnumerator Connection()
{
yield return new WaitForSeconds(2f);
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().Build();
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
PlayerStats = new PlayerStats();
Social.localUser.Authenticate((bool success) =>
{
if (success == false)
{
ErrorGoogle.SetActive(true);
}
else if (PlayerStats.Valid)
{
Database();
}
});
}

Unity "SceneManager.activeSceneChanged" getting called when "LoadSceneAsync" and load other scene

first, there is a singleton object simply is subscribed to activeSceneChanged
SomeSingleton.cs
void Awake ()
{
Debug.LogError ("AWAKE");
if (instance == null) {
Debug.LogError ("instance == null");
instance = this;
MusicController.instance = this;
SceneManager.activeSceneChanged += OnSceneChanged;
DontDestroyOnLoad (this.gameObject);
} else {
Debug.LogError ("destroy");
Destroy (this.gameObject);
}
}
void OnSceneChanged (Scene previousScene, Scene changedScene)
{
Debug.LogError ("OnSceneChanged changedScene = " + changedScene.name);
}
from Lobby Scene player moves to Room Scene.
in room scene.
the "Arena" Scene gets preloaded for better game experience.
LoadSceneAsync("Arena")
with allowSceneActivation = false
when player clicks play button, sets allowSceneActivation = true
but when user decides to go back and clicks Leave Button, LoadScene("Lobby") gets called.
At this time in console, it will Log
LOGS
OnSceneChanged changedScene = Lobby // time : 0.793
OnSceneChanged changedScene = Room // time : 3.982
[when player clicks Leave Button]
OnSceneChanged changedScene = Arena // time : 7.583
OnSceneChanged changedScene = Lobby // time : 7.583
like this...
it just gets activated but wont actually load the scene. why is Arena getting activatd? how to solve this problem???
should i do some unload thing to the AsyncLoading?
==== EDITED =====
when leave button clicked
public void LeaveRoom ()
{
print ("Leave Room And Move To Lobby");
SetCanStartIfMasterClient (false);
PhotonNetwork.LeaveRoom ();
AdmobController.DestroyBanner ();
Waiting.instance.StartWaiting (waitingForLeaveRoomData);
SceneFader.instance.LoadSceneWhenFadingComplete (SceneType.Lobby);
}
in SceneFader.cs
public enum SceneFadeType
{
FadeIn = 1,
FadeOut = -1
}
public class SceneFader : MonoBehaviour
{
public static SceneFader instance;
void Awake ()
{
instance = this;
// StartFadeOut
StartFading (SceneFadeType.FadeOut, null);
}
public void LoadSceneWhenFadingComplete (SceneType sceneType)
{
// 1. start Fading
// 2. on fading complete, LoadScene
StartFading
(
fadeType: SceneFadeType.FadeIn,
onFadingComplete: () => {
SceneManager.LoadScene (sceneType.ToString ());
}
);
}
public void LoadSceneWhenFadingCompleteAsync (ScenePreloader scenePreloader)
{
// 1 start preloading scene
// 2 on preloading complete, start fading
// 3 on fading complete LoadScene
scenePreloader.AddOnPreloadCompleteAndTriggerIfLoaded (
onPreloadComplete: () => {
StartFading (
fadeType: SceneFadeType.FadeIn,
onFadingComplete: () => {
scenePreloader.ActivateSceneWhenReady ();
}
);
}
);
}
private void StartFading (SceneFadeType fadeType, Action onFadingComplete)
{
Debug.LogWarning ("StartFAding ");
ScreenFader.instance.BeginFade (fadeType, onFadingComplete);
AudioMasterController.instance.StartFading (fadeType, null);
}
}
in ScenePreloader.cs
public class ScenePreloader : MonoBehaviour
{
Action<float> onPreloadRateChanged;
Action onPreloadComplete;
public AsyncOperation sceneLoader;
public bool isPreloadCompleted;
public void StartPreloadingScene (SceneType sceneType, LoadSceneMode loadSceneMode, Action<float> onPreloadRateChanged = null, Action onPreloadComplete = null)
{
this.onPreloadComplete = onPreloadComplete;
this.onPreloadRateChanged = onPreloadRateChanged;
StartCoroutine (PreloadSceneOperation (sceneType, loadSceneMode));
}
public IEnumerator PreloadSceneOperation (SceneType sceneType, LoadSceneMode loadSceneMode = LoadSceneMode.Single)
{
print ("PreloadSceneOperation sceneType = " + sceneType.ToString ());
sceneLoader = SceneManager.LoadSceneAsync (sceneType.ToString (), loadSceneMode);
sceneLoader.allowSceneActivation = false;
while (!sceneLoader.isDone) {
yield return null;
if (sceneLoader.progress >= 0.9f) {
print ("onPreloadComplete");
isPreloadCompleted = true;
if (onPreloadComplete != null) {
onPreloadComplete ();
}
break;
} else {
if (onPreloadRateChanged != null) {
onPreloadRateChanged (sceneLoader.progress);
}
}
}
}
public void ActivateSceneWhenReady ()
{
sceneLoader.allowSceneActivation = true;
}
public void AddOnPreloadCompleteAndTriggerIfLoaded (Action onPreloadComplete)
{
AddOnPreloadComplete (onPreloadComplete);
if (isPreloadCompleted) {
print ("isAlreadyLoadedTrigeringCallback");
onPreloadComplete ();
}
}
public void AddOnPreloadComplete (Action onPreloadComplete)
{
this.onPreloadComplete += onPreloadComplete;
}
public void SetOnLoadProgressValueChanged (Action<float> onLoadProgressValueChanged)
{
this.onPreloadRateChanged = onLoadProgressValueChanged;
}
}

Xamarin IOS: unable to play mp3 from internet

I read a lot of documentation regarding this problem, but I don't seen any answer.
I have a Xamarin form app that play mp3 sample music from the Groove music service.
On Android, everyhting workd fine.
On Ios, I'm not able to play the sound. I get the URL and it's not possible to ear anything (I was able to play a local mp3)
I see this problem occured also for people using SWIFT : How to play MP3 From URL in iOS
I also found several exemple on the Xamarin forum but no sound neither: https://forums.xamarin.com/discussion/19883/how-do-i-get-the-avplayer-to-play-an-mp3-from-a-remote-url
Here is the code I use:
public class AudioService : IAudio
{
protected string FileName = string.Empty;
protected AVPlayer Player;
public bool IsPlaying { get; private set; }
public void Init(string fileName)
{
//FileName = fileName;
string second = "http://progdownload.zune.net/145/119/034/170/audio.mp3?rid=0b80911a-ba3b-42ec-b17f-c242ba087024-s4-nl-BE-music-asset-location";
FileName = second;
QueueFile();
}
public async void PlayStream(string uri)
{
Init(uri);
System.Diagnostics.Debug.WriteLine("Enter in function");
Player.Play();
System.Diagnostics.Debug.WriteLine("Play sound");
System.Diagnostics.Debug.WriteLine(FileName);
IsPlaying = true;
System.Diagnostics.Debug.WriteLine(IsPlaying);
}
public void Pause()
{
IsPlaying = false;
Player.Pause();
}
public void Stop()
{
IsPlaying = false;
if (Player == null) return;
Player.Dispose();
Player = null;
}
public bool HasFile
{
get { return Player != null; }
}
private void QueueFile()
{
if (string.IsNullOrWhiteSpace(FileName))
{
throw new Exception("No file specified to play");
}
using (var url = NSUrl.FromString(FileName))
{
var test = AVAsset.FromUrl(url);
var playerItem = AVPlayerItem.FromAsset(test);
// if Player is null, we're creating a new instance and seeking to the spot required
// otherwise we simply resume from where we left off.
if (Player == null)
{
Player = AVPlayer.FromPlayerItem(playerItem);
if (Player == null)
{
// todo: what should we do if the file doesn't exist?
return;
}
}
}
}}
(IAudio just implements playstream and stop)
If you click on the url, your browser will be able to play music
http://progdownload.zune.net/145/119/034/170/audio.mp3?rid=0b80911a-ba3b-42ec-b17f-c242ba087024-s4-nl-BE-music-asset-location
Does any one was able to play mp3 from internet
The answer in the info.list file. You need to add this to your info.list:
<key>NSAppTransportSecurity</key><dict>
<key>NSAllowsArbitraryLoads</key>
<true/></dict>
I had the same issue and resolved it.
I've made some cleaning for your code :)
This is what we got, including the detecting the end of playing
public class AudioService
{
#region Members
protected AVPlayer Player;
#endregion
#region Properties
public bool IsPlaying { get; private set; }
public bool HasFile => Player != null;
public Action MediaEnded { get; set; }
#endregion
#region Public Methods
public void PlayStream(string uri)
{
try
{
if (Player != null)
Player.Dispose();
Player = null;
QueueFile(uri);
Player.Play();
IsPlaying = true;
}
catch (Exception ex)
{
IsPlaying = false;
Crashes.TrackError(ex);
}
}
public void Pause()
{
IsPlaying = false;
Player.Pause();
}
public void Stop()
{
IsPlaying = false;
if (Player == null)
return;
Player.Dispose();
Player = null;
}
public void QueueFile(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName))
{
return;
}
using (var url = NSUrl.FromString(fileName))
{
var asset = AVAsset.FromUrl(url);
var playerItem = AVPlayerItem.FromAsset(asset);
if (Player == null)
{
Player = AVPlayer.FromPlayerItem(playerItem);
if (Player == null)
{
return;
}
else
{
NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, OnPlayerDidFinishPlaying, NSObject.FromObject(playerItem));
}
}
}
}
#endregion
#region Private Methods
private void OnPlayerDidFinishPlaying(NSNotification notification)
{
IsPlaying = false;
MediaEnded?.Invoke();
}
#endregion

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