- Home /
Issue With Spare Ammo In Reload Script
Hey, I am new to scripting in Unity and decided to sit down and create some psuedocode for a reload script in C#. I started by listing variables that I believe would play an important role in a reloading script. Everything works just as I planned (to my surprise) however my issue is that when I click 'R' to reload, it subtracts a different number from my variable 'AmmoToReloadFrom' (spare ammo). My first time posting as well so don't be too harsh about any mistakes :) Thank you.
public class ShootGun : MonoBehaviour {
public Rigidbody bullet;
public Transform bulletSpawn;
public float bulletSpeed;
public float AmmoToReloadFrom;
public float MagSize;
public float CurrentAmmo;
public bool CanShoot = false;
void Start () {
}
void Update () {
if (Input.GetButton("Fire1") && CurrentAmmo > 0) {
CanShoot = true;
var bulletPrefab = (Rigidbody)Instantiate(bullet, bulletSpawn.position, bulletSpawn.rotation);
bulletPrefab.rigidbody.AddForce(-transform.right * bulletSpeed);
audio.Play();
CurrentAmmo--;
}
if (Input.GetButton("Reload") && AmmoToReloadFrom > 0) {
CurrentAmmo = MagSize;
AmmoToReloadFrom = AmmoToReloadFrom - 20;
}
}
void OnGUI() {
if (CurrentAmmo <= 0 && AmmoToReloadFrom > 0) {
GUI.Label(new Rect (Screen.width / 2 - 100, Screen.height / 2 - 100, 250, 200), "Press R To Reload");
}
if (AmmoToReloadFrom <= 0 && CurrentAmmo <= 0) {
GUI.Label(new Rect (Screen.width / 2 - 100,Screen.height / 2 - 100, 250, 200), "No Ammo");
}
}
}
Does $$anonymous$$agSize have a value?
What about bullets still in the mag?
Hi $$anonymous$$eat, forgot to mention that yes I assign values to every gun I attach this script to. In this current scenario, I assigned the FN SCAR model a $$anonymous$$agSize of 20. When you say bullets still in the mag I presume you mean the players current ammo which yes I have assigned to be 20. Thanks anyway. Just for heads up for others, the line that I noticed seems to be causing the issue is AmmoToReloadFrom = AmmoToReloadFrom - 20. To me this seems logical, however this does not seems to be the case.
Change
Input.GetButton("Fire1")
to
Input.GetButtonDown("Fire1")
It's just easier to see. It appears that you gun will be firing at a rate of FPS.
Also,
if (Input.GetButton("Reload") && AmmoToReloadFrom > 0)
{
AmmoToReloadFrom = AmmoToReloadFrom - ($$anonymous$$agSize - CurrentAmmo);
CurrentAmmo = $$anonymous$$agSize;
}
This is what I mean by bullets left in clip :)
Ahh I get you. Thanks you so much man! Works perfectly :D Have a good day! Oh by the way, this was the first script that I sat down and came up with from general knowledge - not much but would you have any more constructive criticism at all?