So I'm making a top-down tank shooter game and I want to make a better reloading system than it was before. So I came to the idea that I need some king of progress bar. I knew how to make it so I started doing it. The problem is that it doesn't work properly. As I show in the .gif above, the progress bar don't go down when you shoot second time. Because I'm new to unity, I still don't know everything very good. So I came here, maybe someone could help.
EDIT:
I just found another problem and maybe an answer why I have this problem. The second time my script tries to reload, my "needTimer" bool is false, thus the progress bar is not going down when it's false. The new question would be why it becomes false instead of true?
My reloading script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Reload : MonoBehaviour {
public float ammo;
public Image progress;
public bool alreadyReloading;
public bool needTimer;
void Start () {
alreadyReloading = false;
}
IEnumerator needtimertime(){
yield return new WaitForSeconds (6.5f);
needTimer = false;
}
IEnumerator uztaisyt(){
Debug.Log ("REEELOUUUDING!");
yield return new WaitForSeconds(6.5f);
ammo += 1;
alreadyReloading = false;
}
void Update () {
if (needTimer == true) {
timer ("");
}
if (ammo < 5) {
if(alreadyReloading == false){
needTimer = true;
StartCoroutine(uztaisyt());
alreadyReloading = true;
}
}
if (progress.fillAmount <= 0) {
progress.fillAmount = 1.0f;
}
}
void timer(string tipas){
progress.fillAmount -= Time.deltaTime / 6.5f;
StartCoroutine (needtimertime ());
}
}
When you start the uztaisyt() as a coroutine after shooting the first time (in the animation), needTimer is set to true and in the next Update() call, the needtimertime() coroutine will start. Since both the uztaisyt() and needtimertime() have identical 6.5 second waits, they will not both return on the same frame update because needtimertime() will always be started in the next frame after uztaisyt(). And, since there is no guarantee of the time interval between Update() calls, (see Time and Frame Managment), this interval may be more than expected and needtimertime() could return false in the frame right after uztaisyt() is called after firing the second time.
To ensure that the needtimertime() is always started (if not already running) immediately following a call for uztaisyt() (and called within the same frame update), you could try the following update to Reload script, (basically changes to the Update() method and when/how _isTimerRunning is set).
public class Reload : MonoBehaviour {
public float ammo;
public Image progress;
private bool _alreadyReloading;
private bool _isTimerRunning;
void Start () {
_alreadyReloading = false;
_isTimerRunning = false;
}
IEnumerator needtimertime(){
yield return new WaitForSeconds (6.5f);
_needTimer = false;
}
IEnumerator uztaisyt(){
Debug.Log ("REEELOUUUDING!");
yield return new WaitForSeconds(6.5f);
ammo += 1;
_alreadyReloading = false;
}
void Update () {
if (ammo < 5) {
if(_alreadyReloading == false){
StartCoroutine(uztaisyt());
_alreadyReloading = true;
//this will check for and start the progress bar timer in the same udate call
//so both coroutines finish on the same frame update
if(!_isTimerRunning){
_isTimerRunning = true;
timer ("");
}
}
}
if (progress.fillAmount <= 0) {
progress.fillAmount = 1.0f;
}
}
void timer(string tipas){
progress.fillAmount -= Time.deltaTime / 6.5f;
StartCoroutine (needtimertime ());
}
}
I found my problem and fixed it.
The problem was that needTimer was becoming false. So I found where and removed it.
my new code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Reload : MonoBehaviour {
public float ammo;
public Image progress;
public bool alreadyReloading;
public bool needTimer;
void Start () {
alreadyReloading = false;
needTimer = false;
}
IEnumerator uztaisyt(){
Debug.Log ("REEELOUUUDING!");
yield return new WaitForSeconds(6.5f);
ammo += 1;
alreadyReloading = false;
}
void Update () {
if (ammo < 5.0f) {
if(alreadyReloading == false){
progress.fillAmount = 1.0f;
needTimer = true;
StartCoroutine(uztaisyt());
alreadyReloading = true;
}
if (needTimer == true) {
timer ("");
}
}
}
void timer(string tipas){
progress.fillAmount -= Time.deltaTime / 6.5f;
}
}
Related
So, I have an object. When I press Spin Button, I want it to spin. When I press Stop button, I want it to stop.
It spins fine when its in void Update, but when its in its own function, it does it just once. I tried using loop but still no luck. Can anyone help me please?
Code C#:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class spin : MonoBehaviour
{
public float speed = 500f;
public Button starter;
public Button stopper;
int testing = 200;
void Start () {
Button btn = starter.GetComponent<Button> ();
Button butn = stopper.GetComponent<Button> ();
butn.onClick.AddListener(FidgetSpinnerStop);
btn.onClick.AddListener(FidgetSpinnerStart);
}
void FidgetSpinnerStart ()
{
for (int i = 0; i < testing; i++) {
transform.Rotate (Vector3.up, speed * Time.deltaTime);
Debug.Log ("Test: " + i);
}
}
void FidgetSpinnerStop ()
{
transform.Rotate (Vector3.up, Time.deltaTime);
}
}
Thanks in advance!
The for loop isn't working as expected because you are not waiting for a frame. Basically, it will do all the spinning in one frame and you won't see the changes until the final spin. Waiting for a frame can the done with yield return null; and that requires a coroutine function.
This is better done with a coroutine. You can use boolean variable with a coroutine or you can just use StartCoroutine and StopCoroutine. Start coorutine that spins the Object when the start Button is clicked and then stop the coroutine when the stop Button is clicked.
public float speed = 500f;
public Button starter;
public Button stopper;
bool isSpinning = false;
IEnumerator spinnerCoroutine;
void Start()
{
//The spin function
spinnerCoroutine = spinCOR();
Button btn = starter.GetComponent<Button>();
Button butn = stopper.GetComponent<Button>();
butn.onClick.AddListener(FidgetSpinnerStop);
btn.onClick.AddListener(FidgetSpinnerStart);
}
IEnumerator spinCOR()
{
//Spin forever untill FidgetSpinnerStop is called
while (true)
{
transform.Rotate(Vector3.up, speed * Time.deltaTime);
//Wait for the next frame
yield return null;
}
}
void FidgetSpinnerStart()
{
//Spin only if it is not spinning
if (!isSpinning)
{
isSpinning = true;
StartCoroutine(spinnerCoroutine);
}
}
void FidgetSpinnerStop()
{
//Stop Spinning only if it is already spinning
if (isSpinning)
{
StopCoroutine(spinnerCoroutine);
isSpinning = false;
}
}
Following is a simple class that start and stops spinning an object using two buttons, I hope it makes a starting point of what you are trying to achieve.
public class TestSpin : MonoBehaviour
{
public float speed = 500f;
public Button starter;
public Button stopper;
bool IsRotating = false;
void Start()
{
Button btn = starter.GetComponent<Button>();
Button butn = stopper.GetComponent<Button>();
butn.onClick.AddListener(FidgetSpinnerStop);
btn.onClick.AddListener(FidgetSpinnerStart);
}
void FidgetSpinnerStart()
{
IsRotating = true;
}
void FidgetSpinnerStop()
{
IsRotating = false;
}
void Update()
{
if (IsRotating)
transform.Rotate(0, speed, 0);
}
}
Basically, what I'm trying to do is when pressing Z - it executes function to spin, and X - it executes function to stop spinning. Before, I had UI buttons which worked perfectly fine, now I try doing it by button but nothing happens.
Also, if you can suggest on how to make it start spinning and stop spinning by only pressing "Space" button, that'd be great.
Heres my code so far:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class spin : MonoBehaviour
{
public float speed = 500f;
public Button starter;
public Button stopper;
bool isSpinning = false;
IEnumerator spinnerCoroutine;
void Start()
{
//The spin function
spinnerCoroutine = spinCOR();
//Button btn = starter.GetComponent<Button>();
//Button butn = stopper.GetComponent<Button>();
//butn.onClick.AddListener(FidgetSpinnerStop);
//btn.onClick.AddListener(FidgetSpinnerStart);
if (Input.GetKey(KeyCode.Z)) {
FidgetSpinnerStart();
}
if (Input.GetKey(KeyCode.X)) {
FidgetSpinnerStop();
}
}
IEnumerator spinCOR()
{
//Spin forever untill FidgetSpinnerStop is called
while (true)
{
transform.Rotate(Vector3.up, speed * Time.deltaTime);
//Wait for the next frame
yield return null;
}
}
void FidgetSpinnerStart()
{
//Spin only if it is not spinning
if (!isSpinning)
{
isSpinning = true;
StartCoroutine(spinnerCoroutine);
}
}
void FidgetSpinnerStop()
{
//Stop Spinning only if it is already spinning
if (isSpinning)
{
StopCoroutine(spinnerCoroutine);
isSpinning = false;
}
}
}
Thanks.
There are just two problems in your code:
1.Checking the keypress in the Start() function.
The Start() will be called once while the Update() function will be called every frame.
You need to use the Update() function to constantly poll the input every frame.
2.Using Input.GetKey() function to check for keypress.
The Input.GetKey() function can return true multiple times over several frames. While you may not see any problems now, that's because the isSpinning variable is preventing possible problems but you will run into problems if you want to add more code directly inside the if (Input.GetKey(KeyCode.Z)) code because those code will execute multiple times in a frame.
You need to use the Input.GetKeyDown() function.
public class spin : MonoBehaviour
{
public float speed = 500f;
public Button starter;
public Button stopper;
bool isSpinning = false;
IEnumerator spinnerCoroutine;
void Start()
{
spinnerCoroutine = spinCOR();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Z)) {
FidgetSpinnerStart();
}
if (Input.GetKeyDown(KeyCode.X)) {
FidgetSpinnerStop();
}
}
IEnumerator spinCOR()
{
//Spin forever until FidgetSpinnerStop is called
while (true)
{
transform.Rotate(Vector3.up, speed * Time.deltaTime);
//Wait for the next frame
yield return null;
}
}
void FidgetSpinnerStart()
{
//Spin only if it is not spinning
if (!isSpinning)
{
isSpinning = true;
StartCoroutine(spinnerCoroutine);
}
}
void FidgetSpinnerStop()
{
//Stop Spinning only if it is already spinning
if (isSpinning)
{
StopCoroutine(spinnerCoroutine);
isSpinning = false;
}
}
}
Also, if you can suggest on how to make it start spinning and stop
spinning by only pressing "Space" button, that'd be great
You can do that with KeyCode.Space. Check if Space key is pressed then check the isSpinning variable before starting/stopping the coroutine.
Just replace the Update function above with the one below:
void Update()
{
//Start if Space-key is pressed AND is not Spinning
if (Input.GetKeyDown(KeyCode.Space) && !isSpinning)
{
FidgetSpinnerStart();
}
//Stop if Space-key is pressed AND is already Spinning
else if (Input.GetKeyDown(KeyCode.Space) && isSpinning)
{
FidgetSpinnerStop();
}
}
Your input logic is only executed once, when Start() is executed.
Put it in the Update() method to check for it every frame.
In this case remove the coroutine and put its logic (without the while-loop) into the Update() method aswell.
public class spin : MonoBehaviour
{
[SerializeField]
private float speed = 500f;
[SerializeField]
private Button starter;
[SerializeField]
private Button stopper;
[SerializeField]
bool isSpinning = false;
void Update()
{
if (Input.GetKeyDown(KeyCode.Z))
{
isSpinning = true ;
}
if (Input.GetKeyDown(KeyCode.X))
{
isSpinning = false ;
}
if( isSpinning )
{
transform.Rotate(Vector3.up, speed * Time.deltaTime)
}
}
}
Further reading
So, I have an object. When I press Spin Button, I want it to spin. When I press Stop button, I want it to stop.
It spins fine when its in void Update, but when its in its own function, it does it just once. I tried using loop but still no luck. Can anyone help me please?
Code C#:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class spin : MonoBehaviour
{
public float speed = 500f;
public Button starter;
public Button stopper;
int testing = 200;
void Start () {
Button btn = starter.GetComponent<Button> ();
Button butn = stopper.GetComponent<Button> ();
butn.onClick.AddListener(FidgetSpinnerStop);
btn.onClick.AddListener(FidgetSpinnerStart);
}
void FidgetSpinnerStart ()
{
for (int i = 0; i < testing; i++) {
transform.Rotate (Vector3.up, speed * Time.deltaTime);
Debug.Log ("Test: " + i);
}
}
void FidgetSpinnerStop ()
{
transform.Rotate (Vector3.up, Time.deltaTime);
}
}
Thanks in advance!
The for loop isn't working as expected because you are not waiting for a frame. Basically, it will do all the spinning in one frame and you won't see the changes until the final spin. Waiting for a frame can the done with yield return null; and that requires a coroutine function.
This is better done with a coroutine. You can use boolean variable with a coroutine or you can just use StartCoroutine and StopCoroutine. Start coorutine that spins the Object when the start Button is clicked and then stop the coroutine when the stop Button is clicked.
public float speed = 500f;
public Button starter;
public Button stopper;
bool isSpinning = false;
IEnumerator spinnerCoroutine;
void Start()
{
//The spin function
spinnerCoroutine = spinCOR();
Button btn = starter.GetComponent<Button>();
Button butn = stopper.GetComponent<Button>();
butn.onClick.AddListener(FidgetSpinnerStop);
btn.onClick.AddListener(FidgetSpinnerStart);
}
IEnumerator spinCOR()
{
//Spin forever untill FidgetSpinnerStop is called
while (true)
{
transform.Rotate(Vector3.up, speed * Time.deltaTime);
//Wait for the next frame
yield return null;
}
}
void FidgetSpinnerStart()
{
//Spin only if it is not spinning
if (!isSpinning)
{
isSpinning = true;
StartCoroutine(spinnerCoroutine);
}
}
void FidgetSpinnerStop()
{
//Stop Spinning only if it is already spinning
if (isSpinning)
{
StopCoroutine(spinnerCoroutine);
isSpinning = false;
}
}
Following is a simple class that start and stops spinning an object using two buttons, I hope it makes a starting point of what you are trying to achieve.
public class TestSpin : MonoBehaviour
{
public float speed = 500f;
public Button starter;
public Button stopper;
bool IsRotating = false;
void Start()
{
Button btn = starter.GetComponent<Button>();
Button butn = stopper.GetComponent<Button>();
butn.onClick.AddListener(FidgetSpinnerStop);
btn.onClick.AddListener(FidgetSpinnerStart);
}
void FidgetSpinnerStart()
{
IsRotating = true;
}
void FidgetSpinnerStop()
{
IsRotating = false;
}
void Update()
{
if (IsRotating)
transform.Rotate(0, speed, 0);
}
}
in my project im trying to count the diferent objects and simulate a little animation, for example i have stars in my game, and i want to count the number of stars in the final of the game from 0 trough the number of stars the user got, so i did this:
public void youWin()
{
audio.Stop ();
StartCoroutine (activatePanel ());
}
IEnumerator activatePanel()
{
yield return new WaitForSeconds (3f);
pausePanel2.SetActive (true);
for (int i = 0; i <= stars; i++) {
yield return new WaitForSeconds (0.2f);
starText2.text = i + "";
}
}
my code worked well for 0.3f on the for loop wait for seconds, but it is too slow, i want it for 0.2f, but something strange happen sometimes it get like a bug and the first number seems to go back, it doesn't count right, someone know what is happening?
It very likely that the activatePanel function is being called from another place while it is already running or the script that contains this code is attached to multiple GameObjects and the activatePanel is again, being called by another function. You can use flag to stop this from happening.
If the coroutine function is already running, use yield break; to break out of it.
bool isRunning = false;
IEnumerator activatePanel()
{
//Exit if already running
if (isRunning)
{
yield break;
}
//Not running, now set isRunning to true then run
isRunning = true;
yield return new WaitForSeconds(3f);
pausePanel2.SetActive(true);
WaitForSeconds waitTime = new WaitForSeconds(0.2f);
for (int i = 0; i <= stars; i++)
{
yield return waitTime;
starText2.text = i.ToString();
}
//Done running, set isRunning to false
isRunning = false;
}
Well i solved it with all of you guys help, actually you all where right, i thaught i was calling the youWin function just 1 time, but i forgot this is unity and i called the youWin inside a trigerEnter function, that means that the object keep enter the triger function and called the youWin function, thank you all here is what i mean with that
Solved it with the bool entered
public class Victory : MonoBehaviour {
Manager gameManager;
// Use this for initialization
public AudioClip clip;
private AudioSource audio;
public Animator girl;
private bool entered;
void OnTriggerEnter(Collider c)
{
if (c.gameObject.tag == "Player" && !entered) {
gameManager.win = true;
audio.clip = clip;
audio.Play ();
gameManager.Ball.GetComponent<MoveBall> ().enabled = true;
girl.SetBool ("win",true);
entered = true;
gameManager.youWin ();
}
}
void Start () {
gameManager = GameObject.Find ("GameController").GetComponent<Manager> ();
audio = GetComponent<AudioSource> ();
entered = false;
}
// Update is called once per frame
void Update () {
}
}
I'm still working on the game and i ran into another problem, I'm trying to make an infinite loop which waits for a couple seconds every execute, i currently have:
StartScript.cs
using UnityEngine;
using System.Collections;
using ProgressBar;
public class StartScript : MonoBehaviour {
private ProgressBarBehaviour hunger;
private ProgressBarBehaviour stamina;
private ProgressRadialBehaviour health;
private ProgressBarBehaviour thirst;
public void OnGUI(){
this.hunger = GameObject.Find("hungerBar").GetComponent<ProgressBarBehaviour>();
this.stamina = GameObject.Find("staminaBar").GetComponent<ProgressBarBehaviour>();
this.health = GameObject.Find("healthBar").GetComponent<ProgressRadialBehaviour>();
this.thirst = GameObject.Find("thirstBar").GetComponent<ProgressBarBehaviour>();
this.health.Value = 100f;
this.stamina.Value = 100f;
StartCoroutine ("runHunger");
}
bool addBar(ProgressBarBehaviour target, float percentage){
Debug.Log (percentage);
if ((target.Value + percentage) <= 100f) {
target.IncrementValue (percentage);
return true;
}
return false;
}
bool damageBar(ProgressBarBehaviour target, float percentage){
if ((target.Value - percentage) >= 0f) {
target.DecrementValue (percentage);
return true;
}
return false;
}
bool addRadial(ProgressRadialBehaviour target, float percentage){
if ((target.Value + percentage) <= 100f) {
target.IncrementValue (percentage);
return true;
}
return false;
}
bool damageRadial(ProgressRadialBehaviour target, float percentage){
if ((target.Value - percentage) >= 0f) {
target.DecrementValue (percentage);
return true;
}
return false;
}
IEnumerator runHunger(){
while (true) {
yield return new WaitForSeconds(10f);
/*if (!this.addBar(this.hunger,5f)) {
this.damageRadial(this.health,3f);
}*/
Debug.Log("Time: "+Time.time);
}
}
IEnumerator runHealth(){
while (true) {
}
}
/*
IEnumerator runThirst(){
while (true) {
if (!this.thirst.Add (2)) {
this.health.Damage(8);
}
}
}*/
}
As you guys can see I'm trying to make a while(true){} loop with an yield return new WaitForSeconds(), the idea is that it runs the function in the loop every (in this test case) 10 seconds.
The first time executing works like a charm, it waits for 10 seconds, but after that it only waits for like 0.1 seconds and executes again.
I hope someone can help me with this problem.
There are too many wrong things I currently see in your code.
This:
IEnumerator runHealth(){
while (true) {
}
}
Change it to
IEnumerator runHealth(){
while (true) {
yield return null;
}
}
Also This:
IEnumerator runThirst(){
while (true) {
if (!this.thirst.Add (2)) {
this.health.Damage(8);
}
}
}
Change it to
IEnumerator runThirst(){
while (true) {
if (!this.thirst.Add (2)) {
this.health.Damage(8);
}
yield return null;
}
}
If you are gonna have while(true) in a coroutine, you must have yield return something or it will lock your program. Fix these problems first. It is good to have it just before the closing bracket of the while loop.
I am sure you did this in other scripts too.
Go over the rest of other scripts and do the same thing. Put yield return null inside each while loop in each coroutine function.
ANOTHER BIG MISTAKE:
Remove every code from OnGUI function and put it in Start function like below. The code is being called too several times per frame and that will lead to slow down as you will be creating many many coroutines that never stops due to your while loop in the coroutine function.Putting it in the Start function will call it once.
void Start()
{
this.hunger = GameObject.Find("hungerBar").GetComponent<ProgressBarBehaviour>();
this.stamina = GameObject.Find("staminaBar").GetComponent<ProgressBarBehaviour>();
this.health = GameObject.Find("healthBar").GetComponent<ProgressRadialBehaviour>();
this.thirst = GameObject.Find("thirstBar").GetComponent<ProgressBarBehaviour>();
this.health.Value = 100f;
this.stamina.Value = 100f;
StartCoroutine ("runHunger");
}
Call the StartCoroutine ("runHunger");
somewhere other than in OnGUI(). It will work then. Since everytime OnGUI is called it starts a new coroutine
Call the StartCoroutine in Start() or someplace else