Show Unity Ads Every 5 times scene is loaded. (Unity 3D) - c#

I want to show ads in my 2D game every 5 times the scene is loaded. I tried this:
void Update ()
{
if(GameObject.Find ("Main Camera").transform.position.x == -23) {
showNumber += 1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
if(showNumber > 5) {
showNumber = 1;
}
}
}
How do I make the number only change only once so it would only change once when the main camera's position is -23. Right not it changes every frame.
Edit
void OnTriggerEnter(Collider other) {
DontDestroyOnLoad (gameObject);
if(other.name == "Main Camera") {
showNumber +=1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
if(showNumber > 5) {
showNumber = 0;
}
}
}

Solution: Put the showNumber +=1 oder showNumber++ into
void Start()
{
showNumber +=1;
}
I think it would be easier if you write this value to a textfile and then read it from this textfile, all in the start event and not the update.
Start is called once and the update is called every frame.
Quick and dirty Edit: Place a trigger zone on your desired postion.
Then call an OnTriggerEnter method.
void OnTriggerEnter(Collider other) {
showNumber +=1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
Edit: Your problem is that showNumber +=1; is called like 30-60 times, depending on your computer.
You could add a bool variable to check if it's a new entry on that point.
bool alreadyEntered = false;
void Update ()
{
if(GameObject.Find ("Main Camera").transform.position.x == -23 && alreadyEntered == false) {
showNumber += 1;
alreadyEntered = true;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
if(showNumber > 5) {
showNumber = 1;
}
}
}

Save the Show Number in player prefs.
private int showNumber{
get{
return PlayerPrefs.GetInt("showNumber");
}
set{
PlayerPrefs.SetInt("showNumber",value);
}
}
void OnTriggerEnter(Collider other) {
showNumber +=1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
showNumber = 0;
}
}

Related

Detecting multiple platforms- c# wpf

I'm making a platformer for my A Level programming project where the player automatically jumps on a platform upon touching it. However, I'm having trouble with the collision detection because it only bounces on one platform and falls right through the rest. they all have the same tags so i know that's not the issue.
the way that it's coded is that it will detect collision with any rectangle with the tag 'platform' however it only detects collision with 1 rectangle
Code sample below:
public partial class MainWindow : Window
{
private DispatcherTimer GameTimer = new DispatcherTimer();
private bool LeftKeyPressed, RightKeyPressed, gravity;
double score;
//this value will increase to be 5x the highest Y value so the score increases the higher Meke gets
private float SpeedX, SpeedY, FrictionX = 0.88f, Speed = 1, FrictionY = 0.80f;
//SpeedX controls horizontal movement, SpeedY controls vertical movement
private void Collide(string Dir)
{
foreach (var x in GameScreen.Children.OfType<Rectangle>())
{
if (x.Tag != null)
{
var platformID = (string)x.Tag;
if (platformID == "platform")
{
x.Stroke = Brushes.Black;
Rect MeekHB = new Rect(Canvas.GetLeft(Meek), Canvas.GetTop(Meek), Meek.Width, Meek.Height);
Rect PlatformHB = new Rect(Canvas.GetLeft(x), Canvas.GetTop(x), x.Width, x.Height);
int Jumpcount = 1;
if (MeekHB.IntersectsWith(PlatformHB))
{
if (Dir == "y")
{
while (Jumpcount != 700)
{
gravity = false;
Jumpcount = Jumpcount + 1;
}
}
}
else
{
gravity = true;
}
}
}
}
}
private void KeyboardUp(object sender, KeyEventArgs e)
{
//this is what detects when the 'A' key is being pressed
if (e.Key == Key.A)
{
LeftKeyPressed = false;
}
if (e.Key == Key.D)
{
RightKeyPressed = false;
}
}
private void KeyboardDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.A)
{
LeftKeyPressed = true;
}
if (e.Key == Key.D)
{
RightKeyPressed = true;
}
}
public MainWindow()
{
InitializeComponent();
GameScreen.Focus();
GameTimer.Interval = TimeSpan.FromMilliseconds(16);
GameTimer.Tick += GameTick;
GameTimer.Start();
}
private void GameTick(Object Sender, EventArgs e)
{
txtScore.Content = "Score: " + score;
if (LeftKeyPressed)
{
SpeedX -= Speed;
}
if (RightKeyPressed)
{
SpeedX += Speed;
}
if (gravity == true)
{
SpeedY += Speed;
}
else if (gravity == false)
{
SpeedY -= Speed+50;
}
SpeedX = SpeedX * FrictionX;
SpeedY = SpeedY * FrictionY;
Canvas.SetLeft(Meek, Canvas.GetLeft(Meek) + SpeedX);
Collide("x");
Canvas.SetTop(Meek, Canvas.GetTop(Meek) + SpeedY);
Collide("y");
double maxY = 0;
if (Canvas.GetBottom(Meek) > maxY)
{
maxY = Canvas.GetBottom(Meek);
}
score = maxY;
}
}
}
I think there is an error in your gravity = true logic. You make check for intersections in loop for all platforms, so even if first platform in loop sets gravity to false, next platform in loop will set gravity to true again and logic won't work. As far as I understand, your logic works only to detect last platform in GameScreen.Children.OfType(). Maybe try to break; you loop after you found an intersection.
And for future - add some logs to your app to be able to debug such issues. Most likely your game library provide some ways to print debug messages - add them to your code so you can see, what's going on.
And also your while (Jumpcount != 700) loop looks useless

How to increase health when score has reached

I'm making a endless runner game. And would like to increase the health/life when a certain score has reached. In a ScoreManager script attached to a ScoreManager I have:
public class ScoreManager : MonoBehaviour
{
public int score;
public Text scoreDisplay;
bool one = true;
Player scriptInstance = null;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Obstacle"))
{
score++;
Debug.Log(score);
}
}
// Start is called before the first frame update
void Start()
{
GameObject tempObj = GameObject.Find("ghost01");
scriptInstance = tempObj.GetComponent<Player>();
}
// Update is called once per frame
private void Update()
{
scoreDisplay.text = score.ToString();
if (scriptInstance.health <= 0)
{
Destroy(this);
}
if (score == 75 || score == 76 && one == true)
{
scriptInstance.health++;
one = false;
}
}
I used the following lines to increase the health at a milestone, but have to copy the code endlessly to create multiple milestones.
if (score == 75 || score == 76 && one == true)
{
scriptInstance.health++;
one = false;
}
My question is how to increase health every 75 points, without duplicating the code?
The issue with a modulo like if(score % 75 == 0) would be that it returns true all the time while score == 75 .. so it would require an additional bool flag anyway.
I would rather simply add a second counter for this!
And not check things repeatedly in Update at all but rather the moment you set it:
int healthCounter;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Obstacle"))
{
score++;
Debug.Log(score);
// enough to update this when actually changed
scoreDisplay.text = score.ToString();
healthCounter++;
if(healthCounter >= 75)
{
scriptInstance.health++;
// reset this counter
healthCounter = 0;
}
}
}
the one drawback maybe is that know you have to reset the healthCounter = 0 wherever you reset the score = 0 ... but you would have to do the same with any flag solution as well ;)
I would go with th % operator
private bool scoreChanged = false;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Obstacle"))
{
score++;
scoreChanged = true;
Debug.Log(score);
}
}
if (score % 75 == 0 && scoreChanged)
{
scriptInstance.health++;
scoreChanged = false;
}

c# Platform game optimization issue + player studdering

This is my first question on stackoverflow, sorry if I made stupid mistakes,
I hope you can help me out!
So my game looks kinda laggy when i Run it, my player studders and if I add gifs instead of image's then everything is very slow :/
I used pictureboxes as Image's
Here is my code (I just used one class):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectBlok1Remake
{
public partial class myGame : Form
{
bool jump = false;
bool right = false;
bool left = false;
int score = 0;
int jumpspeed = 10;
int force = 8;
System.Media.SoundPlayer sp = new System.Media.SoundPlayer("muziek.wav");
public myGame()
{
InitializeComponent();
sp.Play(); // play music :)
}
private void myGame_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
{
right = true;
}
if (e.KeyCode == Keys.Left)
{
left = true;
}
if (e.KeyCode == Keys.Escape)
{
this.Close(); //exist the game
}
if (jump != true)
{
if (e.KeyCode == Keys.Space)
{
jump = true;
}
}
}
private void myGame_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
{
right = false;
}
if (e.KeyCode == Keys.Left)
{
left = false;
}
if (jump)
{
jump = false;
}
}
private void AddPoints(int valueCoin)
{
score = valueCoin + score;
}
private void GameTimer(object sender, EventArgs e)
{
player.Top += jumpspeed;
if (jump && force < 0)
{
jump = false;
}
if (left)
{
player.Left -= 5;
}
if (right)
{
player.Left += 5;
}
if (jump)
{
jumpspeed = -12;
force -= 1;
}
else
{
jumpspeed = 12;
}
foreach (Control x in this.Controls)
{
if (x is PictureBox && x.Tag == "platform")
{
if (player.Bounds.IntersectsWith(x.Bounds) && !jump)
{
force = 8;
player.Top = x.Top - player.Height;
}
}
if (x is PictureBox && x.Tag == "coin")
{
if (player.Bounds.IntersectsWith(x.Bounds) && !jump)
{
this.Controls.Remove(x); //will remove current touched coin :)
AddPoints(5); // each coin taken, will increase the score with 5 points!
}
}
if (x is PictureBox && x.Tag == "bigCoin")
{
if (player.Bounds.IntersectsWith(x.Bounds) && !jump)
{
this.Controls.Remove(x); //will remove current touched coin :)
AddPoints(15); ; // each coin taken, will increase the score with 15 points!
}
}
this.scoreLabel.Text = "score: " + score;
}
if (player.Bounds.IntersectsWith(door.Bounds))
{
timer1.Stop();
sp.Stop();
MessageBox.Show("Congratulations! YOU WON THE GAME! + \n With a total score of: " + score + "\n Exit the game with escape (2x)");
}
if (player.Bounds.IntersectsWith(panel1.Bounds))
{
timer1.Stop();
sp.Stop();
MessageBox.Show("YOU DIED, GAME OVER! :c");
}
}
}
}
Here is an Image of how the game looks like, All the Image's you see are uploaded from a file.
https://i.stack.imgur.com/8QiIc.png
...but if i delete that, there is no gravity and he can't jump.... I didn't say to delete it. I just pointed the problem of changing the position of the player prior the intersect checking. The way you do it is to chech if the new position is ok then change it:
CODE:
private void GameTimer(object sender, EventArgs e)
{
//Don't change the position of the player but a copy one, playerClone!
Rectangle playerClone = player.Bounds;
playerClone.Y += jumpspeed;
if (jump && force < 0)
{
jump = false;
}
if (left)
{
playerClone.X -= 5;
}
if (right)
{
playerClone.X += 5;
}
if (jump)
{
jumpspeed = -12;
force -= 1;
}
else
{
jumpspeed = 12;
}
foreach (Control x in this.Controls)
{
if (x is PictureBox && x.Tag == "platform")
{
if (playerClone.IntersectsWith(x.Bounds) && !jump)
{
force = 8;
playerClone.Y = x.Top - playerClone.Height;
}
}
if (x is PictureBox && x.Tag == "coin")
{
if (playerClone.IntersectsWith(x.Bounds) && !jump)
{
this.Controls.Remove(x); //will remove current touched coin :)
AddPoints(5); // each coin taken, will increase the score with 5 points!
}
}
if (x is PictureBox && x.Tag == "bigCoin")
{
if (playerClone.IntersectsWith(x.Bounds) && !jump)
{
this.Controls.Remove(x); //will remove current touched coin :)
AddPoints(15); ; // each coin taken, will increase the score with 15 points!
}
}
this.scoreLabel.Text = "score: " + score;
}
if (playerClone.IntersectsWith(door.Bounds))
{
timer1.Stop();
sp.Stop();
MessageBox.Show("Congratulations! YOU WON THE GAME! + \n With a total score of: " + score + "\n Exit the game with escape (2x)");
return;
}
if (playerClone.IntersectsWith(panel1.Bounds))
{
timer1.Stop();
sp.Stop();
MessageBox.Show("YOU DIED, GAME OVER! :c");
return;
}
//And now set the player position
player.Bounds = playerClone;
}

Unity3d Pause Button doesn't pause game onClick()

I've made a unity3d game and I want to add UI . I've started with a pause button but it doesn't seem to work.
Here is the button info:
I've created an uiManager script to manage the button , as shown in the image above and here is the code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class myUIManager : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void Pause() //Function to take care of Pause Button..
{
print("Entered Pause Func");
if (Time.timeScale == 1 && paused == false) //1 means the time is normal so the game is running..
{
print("Enterer first if");
Time.timeScale = 0; //Pause Game..
}
if (Time.timeScale == 0)
{
Time.timeScale = 1; //Resume Game..
}
}
}
Here is the canvas screenshot :
Any ideas? I've been searching for hours ..
I think your problem is in your Pause method:
public void Pause() //Function to take care of Pause Button..
{
print("Entered Pause Func");
if (Time.timeScale == 1 && paused == false) //1 means the time is normal so the game is running..
{
print("Enterer first if");
Time.timeScale = 0; //Pause Game..
}
if (Time.timeScale == 0)
{
Time.timeScale = 1; //Resume Game..
}
}
If you enter the first if statement you set Time.timeScale = 0 - and then you immediately go into the second if and set it back to 1.
Try this - it returnss from the Pause method once it sets the Time.timeScale to 0.
public void Pause() //Function to take care of Pause Button..
{
print("Entered Pause Func");
if (Time.timeScale == 1 && paused == false) //1 means the time is normal so the game is running..
{
print("Enterer first if");
Time.timeScale = 0; //Pause Game..
return;
}
if (Time.timeScale == 0)
{
Time.timeScale = 1; //Resume Game..
}
}
If the only two things you want to do in your Pause method are to set the Time.timeScale to 0 or 1, you could even simplify it to this:
public void Pause() //Function to take care of Pause Button..
{
print("Entered Pause Func");
if (Time.timeScale == 1 && paused == false) //1 means the time is normal so the game is running..
{
print("Enterer first if");
Time.timeScale = 0; //Pause Game..
}
else
{
Time.timeScale = 1; //Resume Game..
}
}
if the condition of your first if statement is true then you set your timeScale to 0 then the condition of the second if becomes true then you set it back to 1 You should just change your second if to an else if so that if the first condition is true then your program wont check the second one.
public void Pause()
{
if (Time.timeScale == 1)
{
Time.timeScale = 0;
}
else if (Time.timeScale == 0)
{
Time.timeScale = 1; //Resume Game..
}
}

Making enemy sensors not detect you immediately

I'm working on making a drone-type enemy that has a sensor that sticks out in front of it. I've been stuck on it for a while now, the problem is that I want the drone to not attack immediately after it detects the player, and for it to stay in suspicious mode a little while after the player leaves the drone's field of view. I'm relatively new to coding so my code is a bit of a mess.
void Update () {
if (dTect == true && dTime > -1.6) {
dTime -= Time.deltaTime;
if (dTime < -1.5f) {
aTak = true;
animator.SetTrigger ("Host");
animator.ResetTrigger ("Susp");
} else {
dTect = false;
//animator.ResetTrigger ("Susp");
}
}
if (dTect == false && dTime > 2.1) {
dTime += Time.deltaTime;
}
if (dTime > 2) {
aTak = false;
animator.SetTrigger ("Susp");
animator.ResetTrigger ("Host");
}} void OnTriggerEnter2D(Collider2D other){
if (other.gameObject.CompareTag("Player")){
dTime = 0;
dTect = true;
animator.SetTrigger("Susp");
}
}
void OnTriggerExit2D(Collider2D other){
if (other.gameObject.CompareTag ("Player")) {
dTime = 0;
dTect = false;
}
}
Any help or advice at all would be greatly appreciated.
void Update()
{
if (dTect == true)
{
dTime += Time.deltaTime;
if (dTime >= 1.5f)
{
aTak = true;
animator.SetTrigger("Host");
animator.ResetTrigger("Susp");
dTect = false;
}
}
if (aTak == true)
{
Attack();
}
}
public void Attack()
{
//fill in whatever you want it to do when attacking
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
dTime = 0;
dTect = true;
sPect = false;
animator.SetTrigger("Susp");
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
dTime = 0;
sPect = true;
dTect = false;
aTak = false;
}
}
I believe the problem was with the timers not adding up correctly and not setting the bools to the right state. Also I would highly recommend looking into using an enum for states instead of booleans, they're a lot easier to use cause you don't have to turn off every other state to change it. Good luck with your game and let me know if this wasn't the solution or if you have any other questions :)

Categories