ok so im making an fps game and im trying to add a reloading feature and its supposed to reload only once but for some reason the reload function gets called repeatedly. Any Fix?
here’s my script:
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using UnityEngine;
public class AkShooting : MonoBehaviour
{
public int MaxAmmo = 5;
private int CurrentAmmo;
public GameObject ImpactEffect;
public ParticleSystem MuzzleFlash;
public Camera FpsCam;
public float FireRate = 100f;
private float NextTimeToFire = 0f;
public float damage = 10f;
public float Range = 50f;
public Animator animator;
public bool ableToFire = true;
//AMMO
public int maxAmmo = 10;
public int currentAmmo;
public float ReloadTime = 2f;
public bool isReloading = true;
public bool ableToReload = false;
void Start()
{
currentAmmo = maxAmmo;
Cursor.lockState = CursorLockMode.Locked;
CurrentAmmo = MaxAmmo;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
if (ableToFire = true && Input.GetButton(“Fire1”) && Time.time >= NextTimeToFire && CurrentAmmo > 0 )
{
NextTimeToFire = Time.time + 3f / FireRate;
Shoot();
}
if (CurrentAmmo <= 0 && ableToReload = false)
{
StartCoroutine(Reload());
return;
}
void Shoot()
{
CurrentAmmo–;
MuzzleFlash.Play();
RaycastHit Hit;
if( Physics.Raycast(FpsCam.transform.position, FpsCam.transform.forward, out Hit, Range))
{
EnemyHealth enemy = Hit.transform.GetComponent();
if (enemy != null)
{
enemy.TakeDamage(damage);
}
GameObject impactGO = Instantiate(ImpactEffect, Hit.point, Quaternion.LookRotation(Hit.normal));
Destroy(impactGO, 0.1f);
}
}
IEnumerator Reload()
{
ableToFire = false;
UnityEngine.Debug.Log(“Reloading…”);
yield return new WaitForSeconds(ReloadTime);
currentAmmo = maxAmmo;
ableToFire = true;
ableToReload = false;
}
}
}