Unity MobAd Rewarded Video is not functioning - c#

i have got a strange issue. I've implemented an ad code to the my game and when my player dies, im asking that the player would watch the ad and reborn. When i build and install the apk to my phone, in first play everything works very well. After second attemp, my rewarderAdd.OnAdRewarded function is not working at all. Im controlling the ad state in the game and in second play, i can see that the reward system is not functionning. here is my code
void Start()
{
adState = 0;
gameOverScript = GameObject.Find("GameOver").GetComponent<GameOverCode>();
kingSCript = GameObject.FindGameObjectWithTag("Player").GetComponent<RedKing>();
isCompleted = false;
RequestRewardedVideo();
this.rewardedAd.OnAdRewarded += RewardPlayer;
// this.rewardedAd.OnAdClosed += PlayerClosed;
}
public void RequestRewardedVideo()
{
rewardedAd = RewardBasedVideoAd.Instance;
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the rewarded ad with the request.
this.rewardedAd.LoadAd(request,rewarderID);
if(rewardedAd.IsLoaded() == true)
{
adState = 5;
}
}
private void RewardPlayer(object sender, EventArgs e)
{
isCompleted = true;
adState = 1;
Reward();
}
private void PlayerClosed(object sender, EventArgs e)
{
if(adState != 1)
{
adState = -1;
}
}
public void Reward()
{
adState = 1;
kingSCript.Reborn();
}
public void ShowVideoRewardAd()
{
if (this.rewardedAd.IsLoaded())
{
adState = 2;
isLoaded = true;
this.rewardedAd.Show();
}
else
{
isLoaded = false;
}
}
Why the ad state is not working in second attemp? Every time i re-upload the scene so every code should work as like as the first time but its not working at all!

the solution is use -= functions for all of the methods. check this script out
void Start()
{
gameOverScript = GameObject.Find("GameOver").GetComponent<GameOverCode>();
kingScript = GameObject.FindGameObjectWithTag("Player").GetComponent<RedKing>();
adState = 0;
rewardedID = "ca-app-pub-3940256099942544/5224354917";
rewardedAd = RewardBasedVideoAd.Instance;
isAdLoaded = false;
RequestRewardedAd();
}
void Update()
{
Debug.Log(adState);
if (rewardedAd.IsLoaded())
{
isAdLoaded = true;
Debug.Log("burda");
}
if(adState == 1)
{
kingScript.Reborn();
}
if(adState == -1)
{
gameOverScript.FinishTheGame();
}
}
public void RequestRewardedAd()
{
AdRequest request = AdRequestBuild();
rewardedAd.LoadAd(request, rewardedID);
rewardedAd.OnAdLoaded += this.HandleOnRewardedAdLoaded;
rewardedAd.OnAdRewarded += this.HandleOnAdRewarded;
rewardedAd.OnAdClosed += this.HandleOnRewardedAdClosed;
}
public void HandleOnRewardedAdLoaded(object sender, EventArgs args)
{
Debug.Log("loaded");
adState = 3;
}
public void HandleOnAdRewarded(object sender, EventArgs args)
{
adState = 1;
}
public void HandleOnRewardedAdClosed(object sender, EventArgs args)
{
rewardedAd.OnAdLoaded -= this.HandleOnRewardedAdLoaded;
rewardedAd.OnAdRewarded -= this.HandleOnAdRewarded;
rewardedAd.OnAdClosed -= this.HandleOnRewardedAdClosed;
if(adState != 1)
{
playerAdCount = PlayerPrefs.GetInt("PlayerDontWatchTheAds");
playerAdCount++;
PlayerPrefs.SetInt("PlayerDontWatchTheAds", playerAdCount);
adState = -1;
}
}
public void ShowRewardAd()
{
if (rewardedAd.IsLoaded())
{
rewardedAd.Show();
}
}
AdRequest AdRequestBuild()
{
return new AdRequest.Builder().Build();
}

Related

Why isn't my code increasing the score on reward video ad watched?

When I click a button to load a reward video ad the score should double. Instead the reward ad plays and when I close after watching it, nothing happens. I am using public static variable points to get the score value from the in game scene to the level finished scene, and then I get the total score from player prefabs.
I am new to coding.
Bellow is code.
using GoogleMobileAds.Api;
using System;
using UnityEngine;
using UnityEngine.UI;
public class Admob : MonoBehaviour
{
private BannerView adBanner;
private RewardBasedVideoAd adReward;
int pointts;
int Totalpointts;
private string idApp, idBanner, idReward;
bool saveit = false;
float Timer;
public Text TotalPointsText;
public GameObject congratulationspop;
//public WatchVideo x2coinsWatch;
[SerializeField] Button BtnX2;
// Start is called before the first frame update
[Obsolete]
void Start()
{
//get data
//
idApp = "ca-app-pub-3940256099942544~3347511713";
idBanner = "ca-app-pub-3940256099942544/6300978111";
idReward = "ca-app-pub-3940256099942544/5224354917";
adReward = RewardBasedVideoAd.Instance;
MobileAds.Initialize(idApp);
Debug.LogWarning("Banner Ad Embeded");
RequestBannerAd();
}
// Update is called once per frame
void Update()
{
}
public void GiveRewards()
{
BtnX2.interactable = false;
BtnX2.GetComponentInChildren<Text>().text = "Loading...";
RequestRewardAd();
}
public void RequestBannerAd()
{
adBanner = new BannerView(idBanner, AdSize.Banner, AdPosition.Bottom);
AdRequest request = AdRequestBuild();
adBanner.LoadAd(request);
}
public void DestroyBannerAd()
{
if (adBanner != null)
{
adBanner.Destroy();
}
}
public void RequestRewardAd()
{
AdRequest request = AdRequestBuild();
adReward.LoadAd(request, idReward);
adReward.OnAdLoaded += this.HandleOnRewardedAdLoaded;
adReward.OnAdRewarded += this.HandleOnRewarded;
adReward.OnAdClosed += this.HandleOnRewardedAdClosed;
}
public void ShowRewardAd()
{
if (adReward.IsLoaded())
adReward.Show();
}
public void HandleOnRewardedAdLoaded(object sender, EventArgs args) // Ad Loaded
{
ShowRewardAd();
}
public void HandleOnRewardedAdOpening(object sender, EventArgs args) // Ad Opening
{
}
public void HandleOnRewarded(object sender, EventArgs args) // User Finished Wacthing The Ad
{
// Funtion here to double the coins
x2Thepoints();
}
public void HandleOnRewardedAdClosed(object sender, EventArgs args) // ad closed not watching the
ad
{
BtnX2.interactable = false;
BtnX2.GetComponentInChildren<Text>().text = "X2 Points";
//testing
//testing till here
adReward.OnAdLoaded -= this.HandleOnRewardedAdLoaded;
adReward.OnAdRewarded -= this.HandleOnRewarded;
adReward.OnAdClosed -= this.HandleOnRewardedAdClosed;
}
AdRequest AdRequestBuild()
{
return new AdRequest.Builder().Build();
}
void OnDestroy()
{
DestroyBannerAd();
adReward.OnAdLoaded -= this.HandleOnRewardedAdLoaded;
adReward.OnAdRewarded -= this.HandleOnRewarded;
adReward.OnAdClosed -= this.HandleOnRewardedAdClosed;
}
private void FixedUpdate()
{
Totalpointts = PlayerPrefs.GetInt("points" , Totalpointts);
TotalPointsText.text = "Total Points : " + Totalpointts;
pointts = destination.Mypoint;
Debug.Log(pointts);
if (saveit == true)
{
Timer += Time.deltaTime;
if (Timer >= 2f)
{
Points.inc.OnSavePoint();
saveit = false;
}
}
}
public void x2Thepoints()
{
Totalpointts += pointts;
PlayerPrefs.SetInt("points", Totalpointts);
PlayerPrefs.Save();
saveit = true;
BtnX2.interactable = false;
congratulationspop.SetActive(true);
TotalPointsText.text = "Total Points : " + Totalpointts;
}
}
Set the ad related event handlers before
adReward.LoadAd(request, idReward);
adReward.OnAdLoaded += this.HandleOnRewardedAdLoaded;
adReward.OnAdRewarded += this.HandleOnRewarded;
adReward.OnAdClosed += this.HandleOnRewardedAdClosed;
adReward.LoadAd(request, idReward);
Event handlers are not guaranteed to execute in the Unity main thread. So, force execute them in the next update:
public void HandleOnRewarded(object sender, EventArgs args)
{
MobileAdsEventExecutor.ExecuteInUpdate(() => {
x2Thepoints();
});
}
Unity Google Ads callback events are not guaranteed to be called in the main Unity thread. Try to set you score this way:
public void HandleOnRewarded(object sender, EventArgs args) // User Finished Wacthing The Ad
{
MobileAdsEventExecutor.ExecuteInUpdate(() =>
{
// Funtion here to double the coins
x2Thepoints();
});
}
The method MobileAdsEventExecutor.ExecuteInUpdate runs the callback in the main Unity thread (unity is mono thread).

Admob test Ads not showing in real device ?

I am having a problem because my ads are not showing in my real device but show up in an emulator, I got an error using logcat and this is what I get :
I don't know What to do to solve the problem because I feel like I did everything right.
Some of you may ask for code that may help, well here is my AdManager script, which may seem long but it is easy ..
public static AdManager Instance
{
get;
set;
}
public bool InterstitialLoaded = false;
public bool InterstitialClosed = false;
public string BannerAdId = "ca-app-pub-3940256099942544/6300978111";
public string InterstitialAdId = "ca-app-pub-3940256099942544/1033173712";
InterstitialAd interstitialAd;
AdRequest request;
private BannerView bannerView;
public void requestAds()
{
if (PlayerPrefs.GetInt("NoPersonalized") == 1)
{
request = new AdRequest.Builder().AddExtra("npa", "1").Build();
Debug.Log("NoPersonalized ads EU");
}
else
{
if (PlayerPrefs.GetInt("FirstTime") == 1)
{
if (PlayerPrefs.GetInt("Localized") == 1)
{
//request = new AdRequest.Builder().Build();
request = new AdRequest.Builder().Build();
Debug.Log("Personalized ads EU");
}
}
else if (PlayerPrefs.GetInt("BBb") == 1)
{
if (PlayerPrefs.GetInt("Localized") == 0)
{
request = new AdRequest.Builder().Build();
Debug.Log("personalized No EU");
}
else
{
Debug.Log("First time need select ");
request = new AdRequest.Builder().Build();
}
}
else if (PlayerPrefs.GetInt("NotEU") == 1)
{
Debug.Log("Personalized Not EU ");
request = new AdRequest.Builder().Build();
}
}
}
private void Awake()
{
if (Instance == null)
Instance = this;
else
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
interstitialAd = new InterstitialAd(InterstitialAdId);
Showbanner();
requestAds();
interstitialAd.LoadAd(request);
}
public void RequestBanner()
{
bannerView = new BannerView(BannerAdId, AdSize.Banner, AdPosition.Bottom);
requestAds();
bannerView.LoadAd(request);
bannerView.Show();
}
public void Showbanner()
{
RequestBanner();
}
public void HideBanner()
{
bannerView.Destroy();
bannerView.Hide();
bannerView.Destroy();
}
public void ShowInterstitial()
{
requestAds();
interstitialAd.LoadAd(request);
if (interstitialAd.IsLoaded())
{
InterstitialLoaded = true;
interstitialAd.Show();
}
else
{
}
interstitialAd.OnAdClosed += InterstitialAd_onAdClosed;
}
private void InterstitialAd_onAdClosed(object sender, System.EventArgs e)
{
InterstitialLoaded = false;
InterstitialClosed = true;
}
}
And I get two errors actually the first one is when I call my banner which means I have a problem in that method :
private void Awake()
{
if (Instance == null)
Instance = this;
else
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
interstitialAd = new InterstitialAd(InterstitialAdId);
Showbanner(); // <------- Here
requestAds();
interstitialAd.LoadAd(request);
}
I am having this problem for days now, I wish anyone can help.
Any help would be much appreciated.

Play/Stop MP3 Queue with Naudio or other

I have a problem to stop/pause a Mp3 Queue. Any help please?
I use this class from Githup. it work fine but can't stop it:
public class playr
{
private Queue<string> playlist;
private IWavePlayer player = new WaveOutEvent();
private WaveStream fileWaveStream;
public playr()
{
}
public playr(List<string> startingPlaylist)
{
playlist = new Queue<string>(startingPlaylist);
}
public void PlaySong()
{
if (playlist.Count < 1)
{
return;
}
if (player != null && player.PlaybackState != PlaybackState.Stopped)
{
player.Stop();
}
if (fileWaveStream != null)
{
fileWaveStream.Dispose();
}
if (player != null)
{
player.Dispose();
player = null;
}
player = new WaveOutEvent();
fileWaveStream = new NAudio.Wave.Mp3FileReader(playlist.Dequeue(), new Mp3FileReader.FrameDecompressorBuilder(waveFormat => new NLayer.NAudioSupport.Mp3FrameDecompressor(waveFormat)));
var stream = new BlockAlignReductionStream(fileWaveStream);
player.Init(fileWaveStream);
player.Play();
player.PlaybackStopped += (sender, evn) => { PlaySong(); };
}
}
I popup mp3 files from a datagridview. The goal is playing mp3 sounds and drawing charts.
private void Play_Click(object sender, EventArgs e)
{
try
{
playlist = new List<string>();
for (int item = 0; item < dataGridView1.Rows.Count - 1; item++)
{
playlist.Add(#"mp3Conversion\sounds\" + dataGridView1.Rows[item].Cells["mp3"].Value.ToString());
}
playr playr = new playr(playlist);
playr.PlaySong();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
It wont to stop when I click stop button. is there a way to add a notifier or manage queue ?
private void btnStop_Click(object sender, EventArgs e)
{
try
{
var playr = new playr(playlist);
playr.stopit();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
I hope it's not too late to help you
You can't pause, because you are losing the reference to the object defining a new object
You could try to define the object as static object to solve this problem, but you have to be very careful disposing the object or access to it from multi thread
A very little example
public class playr
{
private Queue<string> playlist;
public static IWavePlayer player = new WaveOutEvent();
// private WaveStream fileWaveStream;
public playr()
{
}
public playr(List<string> startingPlaylist)
{
playlist = new Queue<string>(startingPlaylist);
}
public void PlaySong()
{
if (playlist.Count < 1)
{
return;
}
if (player != null && player.PlaybackState != PlaybackState.Stopped)
{
player.Stop();
}
if (player != null)
{
player.Dispose();
player = null;
}
player = new WaveOutEvent();
var audioFilePath = playlist.First();
var fileWaveStream = new AudioFileReader(audioFilePath);
player.Init(fileWaveStream);
player.Play();
player.PlaybackStopped += (sender, evn) => { PlaySong(); };
}
}
Then you can handle the "player" object from form view

System.Device.Location.GeoCoordinateWatcher.Position.Location.Speed always is NaN

I'm making a simple app for my WP8.1 device, which will be track my maximum speed. I'm using System.Device.Location.GeoCoordinateWatcher for this. I can detect my position, but speed always is NaN. And I don't understand, why. What is wrong? Thanks for any help or info. It is my full code below:
namespace SpeedTracker
{
public partial class MainPage : PhoneApplicationPage
{
GeoCoordinateWatcher watcher;
double maxSpeed = 0.0;
public MainPage()
{
InitializeComponent();
}
private void StartTrackingBtn_Click(object sender, RoutedEventArgs e)
{
this.watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
this.watcher.MovementThreshold = 10;
this.watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
this.watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
this.watcher.Start();
}
private void StopTrackingBtn_Click(object sender, RoutedEventArgs e)
{
this.watcher.StatusChanged -= new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
this.watcher.PositionChanged -= new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
this.watcher.Stop();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (this.watcher.Position.Location.IsUnknown != true)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.maxSpeed = Math.Max(this.maxSpeed, e.Position.Location.Speed);
this.SpeedValueTxblck.Text = this.maxSpeed.ToString();
});
}
else
{
this.SpeedValueTxblck.Text = "Please wait while your prosition is determined...";
}
}
private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.SpeedValueTxblck.Text = "Location Service is not enabled on the device";
});
break;
case GeoPositionStatus.NoData:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.SpeedValueTxblck.Text = "The Location Service is working, but it cannot get location data";
});
break;
default:
break;
}
}
private void GetLocationCourseAndSpeed()
{
this.watcher.TryStart(true, TimeSpan.FromMilliseconds(1000));
if (watcher.Position.Location.IsUnknown != true)
{
GeoCoordinate coord = watcher.Position.Location;
this.maxSpeed = Math.Max(this.maxSpeed, coord.Speed);
this.SpeedValueTxblck.Text = this.maxSpeed.ToString();
}
else
{
this.SpeedValueTxblck.Text = "Unknown";
}
}
}
}
I don't believe that there is an issue with your code. I am doing a similar function on a device that has WiFi, Cellular and GPS installed. It appears that cellular is the fastest to lock in and does not ever provide any speed data. However, when I disable cell and WiFi, I get speed data from the GPS sensor just fine. If you have dedicated GPS, I would try doing the same thing. If not, you may need it to get what you are looking for.

Start a fixed number of process using C#

I want to run say 50 processes but since the machine will choke at 5, I want to run 5 processes at a time and and keep starting the next one as soon as one of the 5 running processes finish. Please advice what's a good way to do this?
I can wait on the last process I launch by Process.WaitForExit but that doesn't do the trick since what if one of the earlier 4 processes finishes first.
Thanks
I had to create a similar bottleneck while writing an app to handle hundreds of Powershell commands. I ended up creating a "queue" class that contained a list of objects. The objects were another custom class that contained the Process and a few events.
I'd loop through the processes, setting them up to be run, then add them to the Queue class. At the end I'd call a RunFirstScripts function that looped through the first 20 in the list and called a Start function, then removed it from the list.
I bound the Exit event to a handler that ran the next server and then removed it from the queue.
class ServerQueue
{
private List<Script> Servers = new List<Script>();
public void Add(Script Server)
{
Servers.Add(Server);
Server.Exited += cmd_Exited;
}
public void RunNextScript()
{
if (Servers.Count > 0)
{
Script ToRun = Servers[0];
Servers.Remove(ToRun);
ToRun.StartProcess();
}
}
public void StartFirstScripts()
{
byte Running = 0;
while (Servers.Count > 0 && Running <= 20)
{
RunNextScript();
Running++;
}
}
private void cmd_Exited(object sender, EventArgs e)
{
RunNextScript();
}
}
EDIT Here's some code for the Script:
class Script
{
public string Output
{
get
{
return pOutput;
}
}
public string Errors
{
get
{
return pErrors;
}
}
public bool IsRunning
{
get
{
return pIsRunning;
}
}
private string pOutput = "";
private string pErrors = "";
private bool pIsRunning = false;
public delegate void OutputEventHandler(Script sender, string Output, bool IsError);
public delegate void StatusEventHandler(Script sender);
public event OutputEventHandler OutputDataReceived;
public event OutputEventHandler ErrorDataReceived;
public event StatusEventHandler Started;
public event StatusEventHandler Exited;
private Process cmd;
public void StartProcess()
{
pIsRunning = true;
cmd.Start();
cmd.BeginOutputReadLine();
cmd.BeginErrorReadLine();
Started(this);
}
public void KillProcess()
{
if (IsRunning)
{
cmd.Kill();
}
}
public void SetupScript()
{
cmd = new Process();
//configure Process (but don't start it yet)
}
private void cmd_Exited(object sender, EventArgs e)
{
pIsRunning = false;
Exited(this);
//do other stuff
}
private void cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
OutputDataReceived(this, e.Data, false);
//do stuff
}
private void cmd_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
ErrorDataReceived(this, e.Data, true);
//do stuff
}
}
There's a tiny race condition, if the planets align correctly you could attempt to start the same process twice but the second attempt should fail (as it's already running) and the way it's set up it's extremely unlikely to ever occur. You can add some extra error trapping if you like, there should probably be a try/catch in StartProcess (this is modified from my own solution and as such missing some context).
EDIT
Here is my Process to work with all these bits:
Process cmd = new Process();
cmd.StartInfo.FileName = "PowerShell.exe";
cmd.StartInfo.Arguments = "-executionpolicy unrestricted -file \"" + TempFile.FullName + "\" -pwd " + Pwd;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.CreateNoWindow = true;
cmd.EnableRaisingEvents = true;
cmd.OutputDataReceived += cmd_UpdateDataReceived;
cmd.ErrorDataReceived += cmd_ErrorDataReceived;
cmd.Exited += cmd_Exited;
here is the edited code for completeness. Full credit to Deadly-Bagel. Thanks,
class ServerQueue
{
private List<Script> Servers = new List<Script>();
public void Add(Script Server)
{
Servers.Add(Server);
Server.Exited += cmd_Exited;
}
public void RunNextScript()
{
if (Servers.Count > 0)
{
Script ToRun = Servers[0];
Servers.Remove(ToRun);
ToRun.StartProcess();
}
}
public void StartFirstScripts()
{
byte Running = 0;
while (Servers.Count > 0 && Running <= 20)
{
RunNextScript();
Running++;
}
}
private void cmd_Exited(object sender, EventArgs e)
{
RunNextScript();
}
}
class Script
{
public string Output
{
get
{
return pOutput;
}
}
public string Errors
{
get
{
return pErrors;
}
}
public bool IsRunning
{
get
{
return pIsRunning;
}
}
private string pOutput = "";
private string pErrors = "";
private bool pIsRunning = false;
public delegate void OutputEventHandler(Script sender, string Output, bool IsError);
public delegate void StatusEventHandler(Script sender, EventArgs e);
public event OutputEventHandler OutputDataReceived;
public event OutputEventHandler ErrorDataReceived;
public event StatusEventHandler Started;
public event StatusEventHandler Exited;
private Process cmd;
public void StartProcess()
{
pIsRunning = true;
cmd.Start();
cmd.BeginOutputReadLine();
cmd.BeginErrorReadLine();
Started(this, null);
}
public void KillProcess()
{
if (IsRunning)
{
cmd.Kill();
}
}
public void SetupScript()
{
cmd = new Process();
cmd.EnableRaisingEvents = true;
cmd.Exited += new EventHandler(cmd_Exited);
//configure Process (but don't start it yet)
}
private void cmd_Exited(object sender, EventArgs e)
{
pIsRunning = false;
Exited(this, null);
//do other stuff
}
private void cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
OutputDataReceived(this, e.Data, false);
//do stuff
}
private void cmd_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
ErrorDataReceived(this, e.Data, true);
//do stuff
}
}

Categories