I have 3 guns in my game and can switch between them using the scroll wheel. The guns reload after their current ammo drops to 0. this is the script for one of them:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Pistol : MonoBehaviour
{
public GameObject pistol;
public ParticleSystem mf;
public float damage = 5f;
public float range = 50f;
public float fireRate = 5f;
public AudioSource audioSource;
public AudioSource reloadSound;
public Camera fpsCam;
private float nextTimeToFire = 0f;
public GameObject impactEffect;
public ParticleSystem ief;
public int maxAmmo = 10;
private int currentAmmo;
public float reloadTime = 2f;
private bool isReloading = false;
public Text ammoText;
void Start()
{
currentAmmo = maxAmmo;
}
// Update is called once per frame
void Update()
{
UpdateBulletText();
if (isReloading)
{
return;
}
if (currentAmmo <=0)
{
UpdateBulletText();
StartCoroutine(Reload());
return;
}
if (Input.GetMouseButtonDown(0) && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
IEnumerator Reload()
{
isReloading = true;
reloadSound.Play();
yield return new WaitForSeconds(reloadTime);
currentAmmo = maxAmmo;
isReloading = false;
UpdateBulletText();
}
void Shoot()
{
currentAmmo--;
audioSource.PlayOneShot(audioSource.clip);
mf.Play();
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range, 1 << 8))
{
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGO, 1f);
}
}
private void UpdateBulletText()
{
ammoText.text = currentAmmo + " / " + maxAmmo;
}
}
The problem is that if i switch guns while reloading after i switch back to the gun that was reloading it is stuck at 0 ammo and doesn’t reload. How can i fix this?