Reload script not working?!
Hello. I'm having problems with my reload script. When I press R, a coroutine starts and initiates the reloading. While the player is reloading I dont want the player to be reloading again...
So in my Weapon.cs script I made a public Bool "CanReload" and by default its set to false.
Here is my script:
public bool CanReload = false;
private void Update()
{
if (magazines <= 0 && ammo <= 0) {
CanReload = false;
} else if (ammo >= 0)
{
CanReload = true;
}
CheckForReload();
}
void CheckForReload()
{
if (Input.GetKeyDown("r") && CanReload == true)
{
StartCoroutine (Reloading());
}
}
IEnumerator Reloading()
{
CanReload = false;
GetComponent<AudioSource>().PlayOneShot (Reload);
yield return new WaitForSeconds (ReloadTime);
ammo = ammoPerMag;
magazines -= 1;
PlayerCanShoot = true;
Debug.LogWarning ("Reloaded!");
CanReload = true;
}
I dont understand why this is not working. When I hit R I am able to reload again and again..
Answer by drawtheplay · Feb 20, 2016 at 02:12 PM
It appears that your setting the CanReload every frame. So while you set it to false in your coroutine it is set back to true before you change your ammo count. I would probably use a setter for your ammo that allows reload.
This might be a decent solution for what you want. Only have the update loop CheckForReload then have the getter setters set your CanReload.
public int Ammo
{
get
{
return ammo;
}
set
{
//don't continue processing if our ammo value is already processed
if(ammo == value)
return;
UpdateIfWeCanReload();
}
}
public int Magazines
{
get
{
return magazines
}
set
{
if(magazines == value)
return;
UpdateIfWeCanReload();
}
}
void UpdateIfWeCanReload()
{
if (magazines <= 0 && ammo <= 0) {
CanReload = false;
} else if (ammo >= 0)
{
CanReload = true;
}
}
Now you will have to change where ever you reference ammo and magazines to use the getter setter.
Hope that helps.
Answer by YoloJoe · Feb 21, 2016 at 09:55 AM
I just removed whole "Else if" statement and it fixed it :) Thanks anyways though :)
Your answer
Follow this Question
Related Questions
If statement not working 1 Answer
Find bool in multiple scenes? 0 Answers
bool not working on another cloned enemy 1 Answer
Get Time A Bool Has Been True 4 Answers
Linecast not working after Instantiation of a particular object 0 Answers