How Can I Reset And Loop This Timer Forever Unity? - c#

I have a button and a timer inside of it when we click it I was wondering how could I make it so I can set the timer back to 0 and if we click the exit button the timer loops again until it's at 80 and goes back to 0 forever?
I have tried several ways adding a ttimer2 = 0 at the end but it would just loop my timer without me clicking the button any help is appreciated thank you!.
if (CrossPlatformInputManager.GetButton("exit"))
{
if (ttimer2 < 80 && flag2)
{
ttimer2 += 1;
UpDown = 2;
Debug.Log(ttimer);
transform.Translate(Vector3.up * speed * Time.deltaTime);
darkin.SetBool("play", false);
darkengame.SetActive(true);
}
else
{
flag2 = true;
Debug.Log(ttimer);
darkengame.SetActive(false);
}
}

you need reset loops index
int index = 0;
int maxIndex = 80;
if (CrossPlatformInputManager.GetButton("exit"))
{
if (index >= maxIndex && flag2)
{
index = 0;
}
else
{
index++;
}
}

Related

Fire bullets at an interval continuously while the fire button is held down

In C# Unity3D, I'm trying to get my bullets to fire at an interval of bulletTime. Single shots work perfectly fine at the moment, but when I hold down the fire button, just 1 bullet is created and shot and then nothing else happens.
// Left mouse button HELD down.
else if (fireAgain && Input.GetMouseButton(0))
{
StartCoroutine("LoopNShoot");
fireAgain = false;
}
else if (timerH < bulletTime)
{
timerH += Time.deltaTime;
if(timerH >= bulletTime)
{
fireAgain = true;
timerH = 0;
}
}
IEnumerator LoopNShoot()
{
pivot.transform.Rotate(triggerAngle,0,0);
GameObject bullet = ObjectPooler.SharedInstance.GetPooledObject();
if (bullet != null) {
bullet.transform.position = SSpawn.transform.position;
bullet.transform.rotation = SSpawn.transform.rotation;
bullet.SetActive(true);
}
yield return new WaitForSeconds(.1f);
pivot.transform.rotation = Quaternion.Slerp(transform.rotation, originalRotationValue, Time.deltaTime * rotationResetSpeed);
}
Im thinking I need to place all my if statements and timer inside the coroutine? But that doesnt seem to help either...
Please ignore the pivot and rotation, it works fine for some animation, the only thing taht doesnt work is shooting bullets continuosly at a set interval while the fire button is Held down.
You should remove these else and just do.
private void Update()
{
if (fireAgain && Input.GetMouseButton(0))
{
StartCoroutine("LoopNShoot");
fireAgain = false;
timerH = 0;
}
if (timerH < bulletTime)
{
timerH += Time.deltaTime;
if(timerH >= bulletTime)
{
fireAgain = true;
}
}
}
You could also re-arange this to make clearer how it works:
private void Update()
{
if(!fireAgain)
{
timerH += Time.deltaTime;
if (timerH >= bulletTime)
{
fireAgain = true;
}
}
else
{
if(Input.GetMouseButton(0))
{
StartCoroutine("LoopNShoot");
fireAgain = false;
timerH = 0;
}
}
}
I actually thought you anyway already chose the Invoke method I showed you here

Problems with my invincibility frames feature

I've been working on a game as a project and I've gotten round to introducing invincibility frames when the player takes a heart of damage. In this case I want it so that the player model flashes roughly once every 0.1 seconds and to have the invincibility last for 2 seconds.
I've written this code and I can't figure out why it isn't working. By the way using this code when the player takes damage they cannot take damage afterwards so something is really messed up (it isn't just the visual invincibility being an issue).
(Thank you)
private void loseHealth()
{
if (invinTimerCounter == 0)
{
curHealth -= 1;
invinTimerCounter = invinTimer;
invincibilityBlink();
}
}
private void invincibilityBlink()
{
for (int i = 0; i < 10; i++)
{
Invoke("spriteDisable", 1);
Invoke("spriteEnable", 1);
}
}
private void spriteEnable()
{
this.spriteRenderer.enabled = true;
}
private void spriteDisable()
{
this.spriteRenderer.enabled = false;
}
private void Update()
{
if (invinTimerCounter < 0)
{
invinTimerCounter -= Time.deltaTime;
}
}
In addition to jmalenfant's comment, I'd like to rewrite your invincibilityBlink() method to use a coroutine:
private IEnumerator invincibilityBlink()
{
for (int i = 0; i < 10; i++)
{
spriteDisable();
yield return new WaitForSeconds(0.1f);
spriteEnable();
yield return new WaitForSeconds(0.1f);
}
invincible = false;
}
Then, here:
if (!invincible)
{
curHealth -= 1;
invincible = true;
StartCoroutine(invincibilityBlink());
}
Oh, and we'll change that messy float to a boolean and let the coroutine handle it too, so if you decide to change the invincibility time, you only need to change things in one place.

Audio playing later than it should

[Unity 5.5.1f1] [C#]
I just made a reloading script which is supposed to play a sound as soon as it starts reloading.
The script works perfectly, but the sound starts playing exactly when it's DONE reloading.
Moving the line up outside of the current if, to under the if (currentClip <= 0 || pressedR == true) doesn't work either.
Does someone know how to let the sound play as soon as the reloading starts? (preferably under if (totalAmmo > 1) so that it won't play when all reserve ammo is also depleted)
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKey(KeyCode.Mouse0) && counter > DelayTime && reloading == false)
{
Instantiate(Bullet, transform.position, transform.rotation); //Spawning the bullet
currentClip += -1;
counter = 0;
}
if (Input.GetKey(KeyCode.R)) //This will allow the player to use "R" to reload.
{
pressedR = true;
}
//Start of reloading
if (currentClip <= 0 || pressedR == true)
{
reloading = true;
if (totalAmmo > 1)
{
GetComponent<AudioSource>().Play(); // <-- AUDIO AUDIO AUDIO
reloadCounter += Time.deltaTime;
if (reloadCounter > reloadTime)
{
missingAmmo = clipSize - currentClip;
if (totalAmmo >= missingAmmo)
{
totalAmmo += currentClip;
totalAmmo += -clipSize;
currentClip = clipSize;
}
else
{
currentClip += totalAmmo;
totalAmmo = 0;
}
reloading = false;
pressedR = false;
reloadCounter = 0;
//End of reloading
}
}
}
counter += Time.deltaTime;
}
What's happening here is that the clip is being played every frame during your reloading process, which keeps restarting it until reloading is done. As a result, you can't heard the clip play out in its entirety until the very end, which is why it seems like the audio is only being played after the reloading process.
To solve this, you should call AudioSource.Play() outside of the reloading logic - preferably when you first trigger the reload to start. However, you currently have multiple entry points into the reloading process - either when the current clip is empty, or when R is pressed. I'd suggest moving both of those conditions into the same if condition, and setting a single flag to start the reloading if either is true. At that point, you can call AudioSource.Play(), so it will only be triggered once per reload:
void FixedUpdate()
{
if (Input.GetKey(KeyCode.Mouse0) && counter > DelayTime && reloading == false)
{
// ...
}
// Start reloading if not already reloading and either R is pressed or clip is empty
if (!reloading && (Input.GetKey(KeyCode.R) || currentClip <= 0))
{
reloading = true;
GetComponent<AudioSource>().Play();
}
//Start of reloading
if (reloading)
{
if (totalAmmo > 1)
{
reloadCounter += Time.deltaTime;
if (reloadCounter > reloadTime)
{
missingAmmo = clipSize - currentClip;
if (totalAmmo >= missingAmmo)
{
totalAmmo += currentClip;
totalAmmo += -clipSize;
currentClip = clipSize;
}
else
{
currentClip += totalAmmo;
totalAmmo = 0;
}
reloading = false;
reloadCounter = 0;
//End of reloading
}
}
}
counter += Time.deltaTime;
}
Note that I appropriated your reloading flag for my purposes, since prior to that it wasn't doing a whole lot. By doing this, I was able to eliminate pressedR from your code, saving on a bit of complexity.
Hope this helps! Let me know if you have any questions.

Why the progressBar never reaches 100%?

What i wanted to do is that if i check if counter == 10 then the progressBar will jump by 10's untill 100.
If i will make if counter == 20 then the progressBar should jump by 20's untill 100.
private void NewsUpdate()
{
counter += 1;
progressBar1.Value = (int)Math.Round((counter / 10f) * 100);
label9.Text = counter.ToString();
label9.Visible = true;
if (counter == 10)
{
Extractions();
counter = 0;
progressBar1.Value = 0;
}
}
Im calling this method in a timer tick event the timer1 interval is set to 1000ms
What happen now is that the progrsssBar1 move by 10's getting to 90% after 9 times it's moving back to 0 to value 0. Wht it's not getting to 100% to the end ?
Do this instead:
PprogressBar1.Maximum = YourMaximumValue; // like for example 1,000,000
and then increment by 1
Counter += 1;
ProgressBar1.Value = Counter;
Your formula in your question results in a decimal which is always less than 100 (Like 98.55).
When the counter equals 10, the progress is 100%. However, you're setting the progressBar1.Value = 0; so it never reaches 100% before the UI can update.

checking a color of a button and changing it using a 2D array

I'm creating a small game just like the game Reversi/Othello I have managed to created a 2x3 board with buttons.
The buttons change colour ones you click on them but I'm having trouble to detect if there is a white colour in between 2 black colours and if so change that white colour into black.. I hope this make sense. the buttons are in a 2D array. Any suggestions that could help me do this would be much appreciated.
The image:
Here is my code:
![namespace reversitest
{
public partial class Form1 : Form
{
private Button\[,\] squares;
public Form1()
{
InitializeComponent();
squares = new Button\[3, 2\];
squares = new Button\[,\] {{button1, button2, button3},
{button4, button5, button6,}};
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (Button sqrr in squares)
{
sqrr.Click += new System.EventHandler(this.DrawCharacter);
}
}
int _turn = 0;
private void DrawCharacter(object sender, EventArgs e)
{
Button sqrr = (Button)sender;
int col = 0;
if (sqrr.BackColor.Equals(Color.Black) || sqrr.BackColor.Equals(Color.White))
{
MessageBox.Show("Move Not Allowed!");
}
else
{
for ( int i = 0; i < squares.GetLongLength(1); ++i)
{
// check othere squares and change color
if (i < 2)
{
for (int f = 0; f < 3; ++f)
{
var ss = squares\[i, f\];
if (ss.BackColor.Equals(Color.Black))
{
MessageBox.Show("we have a black");
//ss = squares\[i, f+1\];
ss.BackColor = Color.Black;
}
else
{
MessageBox.Show("no black");
}
}
}
if (_turn == 0)
{
_turn = 1;
sqrr.BackColor = Color.Black;
}
else
{
_turn = 0;
sqrr.BackColor = Color.White;
}
}
}
}
}
}
First name your buttons with the array index. It will help you to find the button.
For example according to you picture button1 name would be btn_1_1.
Then inside your button click event first get the button name and then identify the button positioned.
Button b = sender as Button;
string[] btnData = b.Name.Split('_');
int x = int.Parse(btnData[1]);
int y = int.Parse(btnData[2]);
//check for possible combinations
int top = y - 2;
int botton = y + 2;
int left = x - 2;
int right = x + 2;
if (top >= 0 && squares[top, y].Background == Color.Black)
{
squares[top+1, y].Background = Color.Black;
}
...
...
Continue like that. If you need more detail please free to ask.
Final Answer
//check for possible combinations
int top = x - 2;
int botton = x + 2;
int left = y - 2;
int right = y + 2;
if (top >= 0 && squares[top, y].BackColor == Color.Black)
{
squares[top + 1, y].BackColor = Color.Black;
}
else if (left >= 0 && squares[x, left].BackColor == Color.Black)
{
squares[x, left + 1].BackColor = Color.Black;
}
else if (left >= 0 && squares[x, left].BackColor == Color.Black)
{
squares[x, left + 1].BackColor = Color.Black;
}
Will be extended for a 8x8 board later on
Do you need it to be elegant? A kind of brute force method: You could check for pieces in the 8 different directions it is possible for them to be aligned. So for example, you start with a black piece. Check the next piece over in one direction. If it's white, keep going and take a note of the position that was white so you can change it to black later. When you finally hit a black piece, change all the stored positions to black and move on to the next direction and repeat the process until you've done all 8 directions.

Categories