- Home /
Help with reloading gun.
I need help with reloading my pistol. The problem I'm having is that on one time when the clip runs out, it runs fine. But then when I have to reload again the next time, it won't wait to do it, it will reload instantly. Sorry if this question has already been answered. Thanks for the help.
pragma strict
var clip : int = 6; var ammo : int = 42; var pistol : GameObject;
function Update () {
if (Input.GetMouseButtonDown(0) && pistol.activeSelf && clip >= 1) {
clip -= 1;
}
if (clip == 0) {
Wait();
}
if (ammo < 0) {
ammo = 0;
}
}
function Wait () {
yield WaitForSeconds (3);
if (clip == 0 && ammo != 0) {
clip += 6;
ammo -= 6;
}
}
You're calling wait function multiple times when clip equals 0
Answer by Serinx · Apr 20, 2018 at 03:57 AM
You should prevent the coroutine from running multiple times using a boolean. Try this:
private bool isReloading = false;
function Update () {
if (Input.GetMouseButtonDown(0) && pistol.activeSelf && clip >= 1) {
clip -= 1;
}
if (clip == 0 && !isReloading) {
Wait();
}
if (ammo < 0) {
ammo = 0;
}
}
function Wait () {
isReloading = true;
yield WaitForSeconds (3);
if (clip == 0 && ammo != 0) {
clip += 6;
ammo -= 6;
isReloading = false;
}
}
Thank you so much! This is exactly what I needed.
Your answer
Follow this Question
Related Questions
Some issues with weapon switching and reloading? 2 Answers
Shooting question 1 Answer
separate script to reload. 0 Answers
Need help... Start Button no longer working!!!!! 0 Answers
how to make a first person controller shooting a target? 0 Answers