Don't reward after canceling the ad - c#

everything works fine. downloading and displaying ads. after showing one gives 1 life. what I want is to not give a prize after canceling the ad. is also annoyed when you leave the ad. how can I make sure that the ad is not killed when it is closed? how can I do it ? is there a function that checks that the ad is fully tracked? or is there a function that checks that the ad is closed? and I can determine the duration of the ads. thank you for your interest
`
// Get singleton reward based video ad reference.
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
// RewardBasedVideoAd is a singleton, so handlers should only be registered once.
this.rewardBasedVideo.OnAdLoaded += this.HandleRewardBasedVideoLoaded;
this.rewardBasedVideo.OnAdFailedToLoad += this.HandleRewardBasedVideoFailedToLoad;
this.rewardBasedVideo.OnAdOpening += this.HandleRewardBasedVideoOpened;
this.rewardBasedVideo.OnAdStarted += this.HandleRewardBasedVideoStarted;
this.rewardBasedVideo.OnAdRewarded += this.HandleRewardBasedVideoRewarded;
this.rewardBasedVideo.OnAdClosed += this.HandleRewardBasedVideoClosed;
this.rewardBasedVideo.OnAdLeavingApplication += this.HandleRewardBasedVideoLeftApplication;
}
public void Update()
{
// Calculate simple moving average for time to render screen. 0.1 factor used as smoothing
// value.
this.deltaTime += (Time.deltaTime - this.deltaTime) * 0.1f;
}
// Returns an ad request with custom ad targeting.
private AdRequest CreateAdRequest()
{
return new AdRequest.Builder()
.AddTestDevice(AdRequest.TestDeviceSimulator)
.AddTestDevice("0123456789ABCDEF0123456789ABCDEF")
.AddKeyword("game")
.SetGender(Gender.Male)
.SetBirthday(new DateTime(1985, 1, 1))
.TagForChildDirectedTreatment(false)
.AddExtra("color_bg", "9B30FF")
.Build();
}
private void RequestRewardBasedVideo()
private void ShowRewardBasedVideo()
{
if (this.rewardBasedVideo.IsLoaded())
{
this.rewardBasedVideo.Show();
}
else
{
MonoBehaviour.print("Reward based video ad is not ready yet");
}
}`
NOTE : cut some small parts because it does not publish the code. it would be enough if you tell me the meaning of not giving a prize only in the cancellation of advertisement.

You subscribe to the OnAdRewarded-event in your code:
this.rewardBasedVideo.OnAdRewarded += this.HandleRewardBasedVideoRewarded;
Your this.HandleRewardBasedVideoRewarded-method will be called when the user has completed watching the video.
You can use OnAdClosed to see if the ad was closed.
Check out all the events here
https://developers.google.com/admob/unity/rewarded-video

Related

Unity method only runs first line of code

I've AdMob test ads fully working in my project.
When the ad is watched the below code should run, however only the first line is being executed, the 2 other lines are being ignored with no error.
public void HandleUserEarnedReward(object sender, Reward args)
{
GameControl.control.life += 1;
GameControl.control.Save();
txtLife.text = GameControl.control.life.ToString();
}
I've placed the same code in another method that I trigger with a button to test.
In this instance the full method is run.
public void runtest()
{
GameControl.control.life += 1;
GameControl.control.Save();
txtLife.text = GameControl.control.life.ToString();
}
If i'm not wrong you are trying to give reward after User watches rewarded video. I had the same problem one time, the problem is that functions that are executing inside of "HandleUserEarnedReward" will NOT be executed on unity's MainThread, but on Google's SDK thread.
There are several solutions:
https://github.com/PimDeWitte/UnityMainThreadDispatcher - Switch to main thread using this. Check readme file to more info.
Create global booleans with false value. Then on "HandleUserEarnedReward" change "isRewarded" boolean to true. Create Update function to check boolean value. Something like:
void Update()
{
if (isRewarded)
{
// do all the actions
// reward the player
isRewarded = false; // to make sure this action will happen only once.
}
}
Use Coroutine. Coroutines autoMagically switch to Unity's MainThread after "yield return"
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
string type = args.Type;
double amount = args.Amount;
Debug.Log(
"HandleRewardBasedVideoRewarded event received for "
+ amount.ToString() + " " + type);
StartCoroutine(AfunctionName());
}
IEnumerator AfunctionName()
{
yield return new WaitForSecondsRealtime(0.1f);
// FB.LogAppEvent("AdmobRewardedView");
Debug.Log("Reward Function Called!!!!!");
GiveReward();
this.RequestRewardBasedVideo();
}

Are my Applovin callbacks working correctly in Unity 3d?

I'm not sure if I've set up my event callbacks correctly, where would these events be firing to? I've setup test ads and all the different types of ads are working correctly.
I've got a game object UI_Menu with my listener attached to it like so
AppLovin.SetUnityAdListener("UI_Menu");
But none of the events are firing
public void ShowInterstitial()
{
Log("Showing interstitial ad");
// Optional: You can call `AppLovin.PreloadInterstitial()` and listen to the "LOADED" event to preload the ad from the network before showing it
// Showing utilizing PreloadInterstitial and HasPreloadedInterstitial
if (AppLovin.HasPreloadedInterstitial())
{
// An ad is currently available, so show the interstitial.
#if UNITY_ANDROID
AppLovin.ShowInterstitialForZoneId("998d2ed211ae3efc"); // For Zone Non-RewardedFullScreen3
#endif
}
else
{
// No ad is available. Perform failover logic...
}
}
void onAppLovinEventReceived(string ev)
{
Debug.Log("called");
Log(ev);
if (ev.Contains("VIDEOBEGAN "))
{
Debug.Log("working");
// An ad was shown. Pause the game.
}
else if (ev.Contains("HIDDENINTER"))
{
// Ad ad was closed. Resume the game.
// If you're using PreloadInterstitial/HasPreloadedInterstitial, make a preload call here.
AppLovin.PreloadInterstitial();
}
else if (ev.Contains("LOADEDINTER"))
{
// An interstitial ad was successfully loaded.
}
else if (string.Equals(ev, "LOADINTERFAILED"))
{
// An interstitial ad failed to load.
}
}

Make Picturebox Bounds "collision" add to score Label

Trying to make a simple C# program where a ship goes through several "checkpoints" and when it's bounds interesect, it adds to the players score, then game ends when you reach the final checkpoint. Can't figure out how to make the score go up and print to the label each time. Thanks!
UPDATE: I can get my boxes to increase the score once, but not on all the other pictureboxes. Also, when I hit the final "spaceport" picturebox I get stuck in a messagebox redirect loop. How do I solve these 2 things? Tutors at school are no help.
public partial class consoleForm : Form
{
public consoleForm()
{
InitializeComponent();
}
private void consoleForm_Load(object sender, EventArgs e)
{
}
private void outputBox_TextChanged(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
int score = (0);
if (ship.Bounds.IntersectsWith(wormhole1.Bounds))
{
score += (1);
userScore.Text = score.ToString();
this.Refresh();
}
else if (ship.Bounds.IntersectsWith(wormhole2.Bounds))
{
score += (1);
userScore.Text = score.ToString();
this.Refresh();
}
else if (ship.Bounds.IntersectsWith(wormhole3.Bounds))
{
score += (1);
userScore.Text = score.ToString();
this.Refresh();
}
else if (ship.Bounds.IntersectsWith(wormhole4.Bounds))
{
score += (1);
userScore.Text = score.ToString();
this.Refresh();
}
if (ship.Bounds.IntersectsWith(spaceport.Bounds))
{
MessageBox.Show("you win");
this.Refresh();
}
}
The problem you've got is, that you're only doing this check once when the form loads, and never again.
Remove the logic from the consoleForm_Load event, and put it in your own method, called CheckScore(), or something else meaningful.
What would be good is to use a timer to check for the intersection every, let's say 100ms (0.1 seconds).
Create a timer:
In your constructor for the consoleForm, create a timer and a handler for it, then Start it. *You could even put it in your already-existing consoleForm_Load event - your choice :)
Like so:
public consoleForm()
{
var timer = new System.Timers.Timer(100); // Create a timer that fires every 100ms (0.1s)
timer.Tick += OnTimer_Tick;
timer.Start();
}
Add an event for the Tick event of the timer:
The OnTimer_Tick you can either "auto create" from VS, or add yourself:
private void OnTimer_Tick(object sender, ElapsedEventArgs e)
{
CheckScore(); // Call your logic method to check the score
}
Do the logic:
If you haven't already, make sure you've created the CheckScore() method using your original logic (that used to be in the consoleForm_Load event).
Final note:
I would seriously consider tidying up your CheckScore() (or whatever you like to call it) method, but that's just me :)
Further final note: there are loads of other ways of creating timers; I'm just being nice and using the most basic use of a Timer in WinForms :)
Hope this helps!
MORE!!!
At the moment, you're creating a new "score" every time you call the CheckScore() method.
In order to store your score, create a private field called _score or similar:
private int _score = 0;
Then, whenever you're adding to the user's score, reference the _score field, and use that to calculate and display:
_score++;
// or your own logic
_score += 20; // etc. etc.
// At the bottom of your logic,
// when you're ready to display the score:
userScore.Text = "Your score: " + _score;
Then, you can reference the _score wherever else you need it in your form.
Such as re-setting it:
private void ResetScore()
{
_score = 0;
}
or checking if the score has reached a certain value:
public void CheckScore()
{
...
// Your other logic to increment the score.
...
if (_score >= 10) // Check if the score has reached a certain value.
{
MessageBox.Show("You reached 10 points! YOU WIN!");
}
}
Bingo! ;)
Ok so your issue is that your only calling your code once - when the form is loaded. You need an update event set up and called regularly with the above code to make it work. Otherwise your code looks quite sound. Look into c# timers to get your update method called.

Find if a full video was watched with unity ads

I am allowing users to be rewarded for watching unity video ads with a button click. When you click the button if the ad is ready it displays a video without the option to skip. I add points to the currency as well.
Advertisement.Show ("rewardedVideoZone");
currency += 10;
The ads run fine, at least in test mode, and you cannot skip them. You are also rewarded the 10 points for watching. The problem is that if I start an ad, close my app, then re-open it the ad is gone and I have the 10 extra points.
Is there a way of finding if a user watched the full video to prevent someone from cheating it?
Yup, there is. What you can use is the ShowOptions.resultCallback event to detect whether the user has finished seeing the ad.
Specifically, the event has a parameter ShowResult, which will have a value of ShowResult.Finished if the user watched the ad completely.
Partial Example
if(Advertisement.IsReady("rewardedVideoZone")) {
var showOptions = new ShowOptions();
showOptions.resultCallback += ResultCallback;
Advertisement.Show("rewardedVideoZone", showOptions);
}
private void ResultCallback (ShowResult result) {
if(result == ShowResult.Finished) {
currency += 10;
}
else {
Debug.Log ("No award given. Result was :: "+result);
}
}
Use this code:
using UnityEngine;
using UnityEngine.Advertisements;
public class UnityAdsExample : MonoBehaviour
{
public void ShowRewardedAd()
{
if (Advertisement.IsReady("rewardedVideo"))
{
var options = new ShowOptions { resultCallback = HandleShowResult };
Advertisement.Show("rewardedVideo", options);
}
}
private void HandleShowResult(ShowResult result)
{
switch (result)
{
case ShowResult.Finished:
Debug.Log("The ad was successfully shown.");
//
// YOUR CODE TO REWARD THE GAMER
// Give coins etc.
break;
case ShowResult.Skipped:
Debug.Log("The ad was skipped before reaching the end.");
break;
case ShowResult.Failed:
Debug.LogError("The ad failed to be shown.");
break;
}
}
}
For more info check the documentations.

How to using Timer in c# to hovering button?

I want to make hovering button in my game. Because when my cursor touch the button it will go to another screen immediately. I don't like this so much. I use xna 4.0 with visual studio 2010 to make this project. (use kinect without wpf)
How to use timer in this case ? Please help me
if (Hand.contian(Button) && holdtime == targetHoldtime)
{
}
You have to manage time by yourself based in elapsed time per frame:
ft = GameTime.Elapsed.TotalSeconds; // Xna
ft= 1/30f; // 30fps
And can be done in similar way to this:
class Button {
public float Duration = 1; // One second
public Rectangle Bounds; // Button boundaries
public float Progress { get{ return Elapsed/Duration; } }
float Elapsed = 0;
public void Update(float ft) {
if (Bounds.Contains( HandPosition ))
{
if (Elapsed<Duration) {
Elapsed += ft;
if (Elapsed>Duration) {
Elapsed = Duration;
OnClick();
}
}
} else {
Elapsed = 0;
}
}
}
I would first suggest that you look through the SDK documentation and the built in KinectInteraction controls. They may provide you with what you are looking for. Most notably SDK 1.7 removed that "HoverDwell" button in favor of a "press" action, which is a more natural interaction in a gesture system. You may want to look at using that motion instead.
If you truly desire a "click on hover" type action, you can look at the code in SDK 1.6 for an example. Several examples are available online at the Kinect for Windows CodePlex repository. The specific control example you are looking for is in the "BasicInteraction-WPF" project, and is called HoverDwellButton.
The "button" is actually a ContentControl which means you can place any content in there to make it a button. It can be a simple image, or a complex Grid. It has all the hooks to fire events when the timer on your hover goes off.
There is a decent amount of complexity in this control, which is what makes it work for a wide range of applications. At the core of the interaction is a simple DispatcherTimer.
private void OnPreviewHandEnter(object sender, HandInputEventArgs args)
{
if (this.trackedHandHovers.FirstOrDefault(t => t.Hand.Equals(args.Hand)) == null)
{
// additional logic removed for answer sanity
var timer = new HandHoverTimer(DispatcherPriority.Normal, this.Dispatcher);
timer.Hand = args.Hand;
timer.Interval = TimeSpan.FromMilliseconds(Settings.Default.SelectionTime);
timer.Tick += (o, s) => { this.InvokeHoverClick(args.Hand); };
this.trackedHandHovers.Add(timer);
timer.Start();
}
args.Handled = true;
}
Notice that the Tick event is calling InvokeHoverClick, which (in part) reads as follows:
public void InvokeHoverClick(HandPosition hand)
{
// additional logic removed for answer sanity
var t = new DispatcherTimer();
t.Interval = TimeSpan.FromSeconds(0.6);
t.Tick += (o, s) =>
{
t.Stop();
var clickArgs = new HandInputEventArgs(HoverClickEvent, this, hand);
this.RaiseEvent(clickArgs);
this.IsSelected = false;
};
t.Start();
}
This now fires an event after a set amount of time. This event can be capture and acted upon to your liking.
Again, I first recommend looking at the newer interactions in SDK 1.7. If you still want a timed hover click action, check out the links above. I used the HoverDwellButton to great effect in several different areas.

Categories

Resources