Hey, right now I have my ads setup so that every time my player dies it shows an ad. However, I want it so that an ad shows every 4 times the player dies. I’ve searched this up and can’t find anything that exactly helps me. Here’s what I’ve got so far:
Hmm, I typed up a response to this before and sent it, but I guess it’s gone? Anyway, As others have said, your player can have a death counter. We can actually use the modulus operator here though to make this a bit cooler. So, if deathCount % 4 == 0, then there is no remainder, and deathCount is a multiple of 4, and we want to show the ad. If deathCount % 4 != 0, it is not a multiple of 4, and we don’t want to show the ad. Here’s a bit of rough code for ya:
private int deathCount = 0;
private void KillPlayer() {
deathCount++;
if (deathCount % 4 == 0) {
ShowAdvertisement();
}
}
private void ShowAdvertisement() {
// Fancy code to show the ad
}
With this method, you won’t need to bother with resetting some death counter variable to zero.
So having seen the other comments, it seems you’re loading a new scene every time the player dies. As a result you need something that saves your data when you switch scenes. (Normally data just gets deleted when you load a new scene)
The best option imho would be to create a static class that saves all the game data you want to transfer between scenes. Like this: (You see this class doesn’t inherit from Monobehavior, so if you create a new script you need to remove the “: Monobehavior”
public static class StaticGameObjects
{
public static int deathCounter = 0;
}
Then you’d change your original code like this:
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Obstacle")
{
//Increases the death counter every time the player dies.
StaticGameObjects.deathCounter++;
//In case that the death Counter reaches 4 show the add and reset the deathCounter
if (StaticGameObjects.deathCounter == 4)
{
showAd();
StaticGameObjects.deathCounter = 0;
}
}
}
I’m just learning how to code now so you are a bit far ahead of me, but couldn’t you just set a variable to count up each time the play dies? Once it hit’s four it will trigger the ad to play and then reset itself back to 0.
Afraid I'm new to C# too, how would I make a variable counter?
Just tried this, doesn't work :/ I added a Debug.Log to see if it worked but nothing appeared in my console.
– hanaan328