Hello! I have created a script that works perfectly, but there is something that is weird, The variable TotalAmmo is the number of bullets the player is towards weapon, and when reloading the spent bullets are subtracted until total ammo is 0. But when Total Ammo has 15 bullets for example and not enough to reach the charger, How would you make those bullets are the recharge? (In short if I have fewer bullets than the weapon that occupies recarge the few bullets that are left, that is total bullets). Thank you!
using UnityEngine;
using System.Collections;
public class Weapon : MonoBehaviour {
public float Damage = 0f;
public float Range = 0f;
public float ImpactForce = 0f;
public float FireRate = 0f;
public int MaxAmmo = 0;
public int TotalAmmo = 0;
public int CurrentAmmo;
public int DesechedBullets;
public int ReloadBullets;
public float ReloadTime = 0;
public float DesechedBullTime = 0;
private bool IsReloading = false;
public Camera FPScam;
public ParticleEmitter MuzzleFlash;
public GameObject HitEffect;
private float NextTimeToFire = 0f;
public AudioClip ShootSound;
void Start()
{
CurrentAmmo = MaxAmmo;
}
void OnEnable()
{
IsReloading = false;
}
void Update () {
if(TotalAmmo <= MaxAmmo)
if(DesechedBullets >= MaxAmmo)
{
DesechedBullets = MaxAmmo;
}
if(TotalAmmo <= 0)
{
TotalAmmo = 0;
CurrentAmmo = 0;
DesechedBullets = 0;
}
if(IsReloading)
return;
if(CurrentAmmo < MaxAmmo)
{
if(Input.GetKeyDown(KeyCode.R))
{
StartCoroutine(Reload());
return;
}
}
if(Input.GetButton("Fire1") && Time.time >= NextTimeToFire)
{
NextTimeToFire = Time.time + 1f/FireRate;
if(CurrentAmmo > 0)
Shoot();
}
}
IEnumerator Reload()
{
IsReloading = true;
Debug.Log("Reloading...");
yield return new WaitForSeconds(ReloadTime - 0.25f);
CurrentAmmo = ReloadBullets;
TotalAmmo -= DesechedBullets;
DesechedBullets = 0;
IsReloading = false;
}
void Shoot()
{
DesechedBullets++;
MuzzleFlash.Emit();
audio.Play();
audio.clip = ShootSound;
CurrentAmmo--;
RaycastHit hit;
if (Physics.Raycast(FPScam.transform.position, FPScam.transform.forward, out hit, Range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if(target != null)
{
target.TakeDamage(Damage);
}
if(hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * ImpactForce);
}
Instantiate(HitEffect, hit.point, Quaternion.LookRotation(hit.normal));
}
}
}