Reserve ammo not displaying on UI
It's kinda dumb, but I'm creating a simple fps and I have a basic gun script. It edits a UI that displays the current ammo in the gun and the current reserve ammo. The gun ammo updates well, but the reserve ammo remains locked at the beginning number.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class weaponScript : MonoBehaviour {
public Transform gunEnd;
public GameObject muzzleFlash;
public Transform gun;
public GameObject ImpactEffect;
private bool isReloading = false;
public Text ammoCounter;
[Header("Gun Info")]
public int damage = 10;
public float range = 100f;
public float shotsPerSecond;
public bool automatic;
float t;
float timeBetweenShots;
public float spreadFactor = 0.02f;
public float reloadTime = 1f;
public int maxAmmo = 10;
public int reserveAmmo = 150;
private int currentAmmo;
void Start()
{
timeBetweenShots = 1 / shotsPerSecond;
currentAmmo = maxAmmo;
}
void Update()
{
ammoCounter.text = currentAmmo + "/" + reserveAmmo;
if(isReloading)
{
return;
}
if(currentAmmo <= 0f || Input.GetKeyDown(KeyCode.R))
{
StartCoroutine(Reload());
return;
}
t += Time.deltaTime;
if(Input.GetButtonDown("Fire1") && !automatic && t >= timeBetweenShots)
{
Shoot();
}
if(Input.GetButton("Fire1") && automatic && t >= timeBetweenShots)
{
Shoot();
}
}
void Shoot()
{
currentAmmo --;
GameObject flash = Instantiate(muzzleFlash, gunEnd.position, gun.rotation) as GameObject;
flash.transform.parent = gameObject.transform;
RaycastHit hit;
if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward + new Vector3(Random.Range(spreadFactor, -spreadFactor), Random.Range(spreadFactor, -spreadFactor), Random.Range(spreadFactor, -spreadFactor)), out hit, range))
{
Debug.Log(hit.transform.name);
Instantiate(ImpactEffect, hit.point, Quaternion.LookRotation(hit.normal));
enemyScript target = hit.transform.GetComponent<enemyScript>();
if(target != null)
{
target.TakeDamage(damage);
}
}
}
IEnumerator Reload()
{
isReloading = true;
Debug.Log("Reloading...");
yield return new WaitForSeconds(reloadTime);
if(maxAmmo - currentAmmo < reserveAmmo)
{
currentAmmo = maxAmmo;
reserveAmmo -= maxAmmo - currentAmmo;
}
if(maxAmmo - currentAmmo >= reserveAmmo)
{
currentAmmo = currentAmmo + reserveAmmo;
reserveAmmo = 0;
}
isReloading = false;
}
}
Comment