Reloading

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;
}
}
}

First:

You’re starting the Reload() coroutine in Update() without much in the way of checks to prevent it happening multiple times. Update runs every frame.

Second:

You need to go back through all of your code. The way to check equality in C# is this operator: ==. However I see in several of your if statements that you are using the assignment operator =. When you do that, rather than checking for equality, you are actually changing the value of the variable you meant to simply check the value of. This is really going to screw things up.

Before First:
Use code tags when posting code

ok i changed that but it still does the same thing. It might have to do with the if statement checking every frame if Ammo reaches zero. how can i change this?