- Home /
The question is answered, right answer was accepted
how do i make a ammo and reload system
I have been making a simple FPS game and have a fairly good script but no matter what i search i can't find a solution that works what i want is a system that auto reloads after the mag of 30 bullets is shot or reloaded with the R key at any point i have completed the reload with r key
Here is my code if anyone has a solution
public GameObject bulletPrefab;
public Transform bulletSpawn;
public float velocity;
private int Ammo;
Animator anim;
private int One = 1;
void Start()
{
Ammo = 30;
anim = gameObject.GetComponent<Animator>();
}
void Update() { if (Input.GetMouseButtonDown (0)) {
if (Ammo > 0)
{
Fire ();
Ammo = Ammo - One;
}
else;
{
anim.SetTrigger ("Reload");
Ammo = 30;
}
}
if (Input.GetKeyDown (KeyCode.R))
anim.SetTrigger ("Reload");
Ammo = 30;
} void Fire() {
var bullet = (GameObject)Instantiate (
bulletPrefab,
bulletSpawn.position,
bulletSpawn.rotation);
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * velocity;
Destroy(bullet, 5.0f);
} }
Answer by Helical · Mar 02, 2018 at 02:45 PM
Oh boy,
Lets try looking into where you fire the ammo
if (Ammo > 0)
{
Fire ();
Ammo = Ammo - One; // <---- Ammo deduction line
}
After your ammo deduction line, you could possibly check if you need a reload
if (Ammo > 0)
{
Fire ();
Ammo = Ammo - One;
if( Ammo == 0 ){
anim.SetTrigger ("Reload");
Ammo = 30;
}
}
However this will mean you will Reload at the same time you will Fire your last bullet. Creating Animator bugs.
Try to put the Reloading into a function, and wait on it.
void Reload(){
anim.SetTrigger ("Reload");
Ammo = 30;
}
Now use the Unity Invoke method, this can call functions after some time https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html
if (Ammo > 0)
{
Fire ();
Ammo = Ammo - One;
if( Ammo == 0 ){
Invoke("Reload", 3f);
}
}
*Note judging by your current code I gave you advice that is in accordance, Nothing here is an actual system or works very well.
@Helical i have figured out what i did wrong but you can bypass the reload if you just spam click is there a way to stop this?
Before shooting check if the reload animation is playing. If it does, then don't allow shooting (or reloading either). Also, don't allow reloading when Ammo == 30 either, to avoid infinitely reloading.
Follow this Question
Related Questions
Fps Movement Velocity Decrease 0 Answers
Renderer on object disabled after level reload 1 Answer
Multiple Cars not working 1 Answer
C# - Ammo in Shoot Array?! 1 Answer
Distribute terrain in zones 3 Answers