i tried to write a weapon fire script, that also has an automatic reload timer, it works well, shoots the bullets, substracts 1 ammunition, and then waits X seconds until it can fire again with the ammo reloaded. The problem is that when it reloaded and has X amount of bullets again, it wont substract anymore, so the second round is infinite. any ideas what i am doing wrong?
using UnityEngine;
using System.Collections;
public class NewWeaponManager : MonoBehaviour {
public GameObject parent;
public GameObject muzzle;
public Texture[] muzzleTexture;
public Rigidbody bulletPrefab;
public bool fireWeapon;
public float velocity = 10.0f;
public float weaponSpeed = 0.1f; // Speed of weapon.
public float weaponScattering = 0.005f;
public bool isSpawning = false;
public int currentAmmunition;
public int maxAmmunition = 25;
public bool muzzleFlashEnabled = false;
public bool reloadWeapon = false;
// Use this for initialization
void Start () {
currentAmmunition = maxAmmunition;
}
// Update is called once per frame
void Update () {
if (muzzleFlashEnabled == true) {
muzzle.gameObject.SetActive(true);
} else {
muzzle.gameObject.SetActive(false);
}
if (currentAmmunition <= 0) {
reloadWeapon = true;
StartCoroutine (ReloadWeapon (5));
CancelInvoke("SpawnBullet");
}
if (fireWeapon == true && isSpawning == false) {
if (reloadWeapon == false) {
muzzleFlashEnabled = false;
isSpawning = true;
InvokeRepeating ("SpawnBullet", 0.001f, weaponSpeed);
}
} else if (fireWeapon == false) {
muzzleFlashEnabled = false;
CancelInvoke("SpawnBullet");
isSpawning = false;
}
}
void SpawnBullet() {
muzzleFlashEnabled = true;
float randomDirX = Random.Range (-weaponScattering, weaponScattering);
float randomDirY = Random.Range (-weaponScattering, weaponScattering);
Quaternion ScatterDirection = new Quaternion (transform.rotation.x + randomDirX, transform.rotation.y + randomDirY, transform.rotation.z, transform.rotation.w);
currentAmmunition -= 1;
Rigidbody newBullet = Instantiate(bulletPrefab, transform.position, ScatterDirection) as Rigidbody;
newBullet.AddForce(transform.forward*velocity, ForceMode.VelocityChange);
newBullet.GetComponent<Ammunition>().parentWeapon = gameObject;
}
public IEnumerator ReloadWeapon(float timer) {
yield return new WaitForSeconds (timer);
reloadWeapon = false;
currentAmmunition = maxAmmunition;
}
}