- Home /
reload script not working well
when i reload the first time it works fine but after the first reload it increase from 4 to 8 and then from 8 to 16 here is the script
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class shootingforshutgun : MonoBehaviour
{
public Transform ponit;
public float Speed =10f;
public GameObject bullet;
bool canshot = false;
int Bullets = 4;
int currentbullet;
bool reloading = false;
void Start()
{
currentbullet = Bullets;
}
// Update is called once per frame
void Update()
{
if(currentbullet <= 0)
{
StartCoroutine(wait());
return;
}
if(Input.GetButtonDown("Fire1"))
{
if (!canshot)
{
A();
A();
A();
A();
currentbullet -= 1;
}
}
}
public void A()
{
if (reloading)
return;
if (!canshot)
{
float x = Random.Range(-0.5f, 0.5f);
float y = Random.Range(-0.5f, 0.5f);
Vector3 a = new Vector3(x, y);
Vector3 c = a + ponit.position;
Instantiate(bullet, c, transform.rotation);
}
}
IEnumerator wait()
{
yield return new WaitForSeconds(2f);
currentbullet = Bullets;
}
}
Comment
Answer by KoenigX3 · May 25, 2020 at 04:10 PM
The problem is that you are starting new coroutines in every frame for about 2 seconds.
void Update()
{
if(currentbullet <= 0 && !reloading)
{
StartCoroutine(wait());
return;
}
}
IEnumerator wait()
{
reloading = true;
yield return new WaitForSeconds(2f);
currentbullet = Bullets;
reloading = false;
}
I included the reloading variable so you can check it on Update. If you are already reloading, you don't need to start the coroutine again. When the reloading finishes, the currentbullet variable will be 4, and it will not reload again until you use the bullets.