- Home /
My gun shoots while I'm reloading
I'm stumped. When I try to reload it reloads normally but if I fire while the gun is doing the animation if anyone can help please do it is really confusing.
using UnityEngine;
using System.Collections;
public class Gun : MonoBehaviour
{
private const int V = 3;
//Decal
public GameObject decalHit;
public float projectileDestroyTimer = 5f;
//Ámmo
public int maxAmmoTotal = 30; // Max ammo to carry Example: 30
public int maxAmmoInClipTotal = 5; // Max ammo total to be able to reload Example: 5
public int curAmmo = 30; // Current reloadable ammo Example: 30
public int ammoInClip = 8; // Current ammo in clip Example: 5
private bool isReloading = false;
//Animation
public string fireAnimation; //Shoot animation
public string clipEmptyAnim; //Clip empty animation
public string reloadAnimation; //Reload animation
public float reloadTime = 1f; // How long it takes to reload
public Animator reloadAnimations;
public Animator ClipEmptyAnimations;
//GameObjects
public GameObject weapon; //Needed for aiming
public ParticleSystem muzzleflash;
public Animator FireAnimation;
public AudioSource GunSounds;
//Raycast
private RaycastHit rayHit;
public float shootDistance = 200f;
//Recoil
private float defaultRecoil = 50f;
public float recoil = 50f;
public float recoilAiming = 10f;
//Aim
public Vector3 aimPos = Vector3.zero;
private Vector3 defaultPos = Vector3.zero;
public float smoothTime; //How long it takes to get to the aiming position
private Vector3 dampVelocity;
private bool aiming = false;
//Audio
private AudioSource audioSource; //Audio source
public AudioClip fireSound; //Sound when shooting
public AudioSource clipEmptySound; //Sound when clip is empty
public AudioSource reloadSound; //Sound when reloading
//Weapon
public int hitDamage = 13;
float LastTimeShot;
public float TimeBetweenShots = 1;
public float fireRate = 20f;
private float nextTimeToFire = 0f;
//Only for testing
int removedAmmoRecently; //Only for testing
void Start()
{
defaultPos = weapon.transform.localPosition;
defaultRecoil = recoil;
audioSource = GetComponent<AudioSource>();
}
void Update()
{
AimDownSight();
if (Input.GetButton("Fire1") && Time.time >=nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
if(Input.GetButtonDown("Fire2") && !isReloading)
{
aiming = !aiming;
}
if (Input.GetKeyDown(KeyCode.R) && !isReloading)
{
StartCoroutine("Reload");
}
}
void Shoot()
{
if(ammoInClip != 0)
{
PlaySound(fireSound);
GunSounds.Play();
muzzleflash.Play();
PlayAnimation(fireAnimation);
GetComponent<Animator>().Play("FireAnimation");
ammoInClip--;
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2f + Random.Range(-recoil, recoil), Screen.height/2f + Random.Range(-recoil, recoil), 0f));
if (Physics.Raycast(ray, out rayHit, shootDistance))
{
GameObject decalClone = (GameObject)Instantiate(decalHit, rayHit.point, Quaternion.LookRotation(rayHit.normal, Vector3.forward));
Destroy(decalClone, projectileDestroyTimer);
DoDamage(rayHit);
}
}
else{
clipEmptySound.Play();
GetComponent<Animator>().Play("ClipEmptyAnimation");
}
Debug.Log("Ammo: " + ammoInClip + "/" + curAmmo);
}
void DoDamage(RaycastHit hit)
{
if(hit.transform.tag == "Enemy")
{
if(hit.transform.GetComponent<EnemyHealth>()) //You can change EnemyHealth, to the name of the script that contains the health of the enemy
{
hit.transform.SendMessage("ApplyDamage", hitDamage, SendMessageOptions.DontRequireReceiver);
}
Debug.Log(hit.transform.name + " has been hit");
}
}
IEnumerator Reload()
{
//If ammoInClip example 5 is equal or greater than 0 and ammoInClip(5) is lower than maxAmmoInClipTotal(The max amount of ammo that can be in a clip) and curAmmo(how much ammo you have like 5/30) is greater than 0
if (ammoInClip >= 0 && ammoInClip < maxAmmoInClipTotal && curAmmo > 0)
{
isReloading = true;
reloadSound.Play();
GetComponent<Animator>().Play("reloadAnimations");
yield return new WaitForSeconds(reloadTime);
removedAmmoRecently = 0; //You can remove this line, it's only for testing.
for (int i = 0; i < maxAmmoInClipTotal; i++)
{
if (ammoInClip == maxAmmoInClipTotal || curAmmo <= 0)
{
break;
}
else
{
ammoInClip++;
curAmmo--;
removedAmmoRecently++; //You can remove this line, it's only for testing. | To check how much ammo has been removed
}
}
isReloading = false;
Debug.Log("Removed " + removedAmmoRecently + " " + "ammo from pocket ammo. Ammo: " + ammoInClip + "/" + curAmmo); //You can remove this line, it's only for testing. | Prints out how much ammo that has been removed, ammo you have in clip, and how much ammo that is left
}
else
{
yield break;
}
}
void PlayAnimation(string anim)
{
if (anim != "")
{
weapon.GetComponent<Animation>().Play(anim);
}
}
void PlaySound(AudioClip clip)
{
if (clip != null)
{
audioSource.PlayOneShot(clip);
}
}
void AimDownSight()
{
if(aiming && weapon.transform.localPosition.normalized != aimPos.normalized)
{
weapon.transform.localPosition = Vector3.SmoothDamp (weapon.transform.localPosition, aimPos, ref dampVelocity, smoothTime);
Debug.Log ("Aiming");
recoil = recoilAiming;
}
if(!aiming && weapon.transform.localPosition.normalized != defaultPos.normalized)
{
weapon.transform.localPosition = Vector3.SmoothDamp (weapon.transform.localPosition, defaultPos, ref dampVelocity, smoothTime);
Debug.Log ("UnAiming");
recoil = defaultRecoil;
}
}
void OnGUI()
{
GUILayout.Label("Ammo: " + ammoInClip + "/" + curAmmo);
}
}
Good day.
$$anonymous$$an, this is a "personal problem" with your script. You need to solve that. Create a bool to prevent that, check the logic toi know why is shooting... move! adapt! act!
Bye!
You could just say: "This is your problem, I'm not going to help you". Which is also... not really helping...
Hello $$anonymous$$etalted.
ITs just to encourage people to solve its problems before come to UA for a help. There are too many posts of people co$$anonymous$$g to ask for help before even google it, of find where is the problem.
He does not have a problem about using a function, component, or know how to achieve something. As you explain in your answer, is a problem of logic, that can be easy solved by debugging the code step by step. If you saw it, I'm sure he also can.
I love to help, and sometimes, best help is just make the user review its own code, with patience. He will get better skills and will not ahve this problem again because he saw by its own where the problem is.
PS: Thanks for your time solving the error.
Bye.
Answer by metalted · May 02, 2019 at 10:18 AM
As I see it now, you are setting the isReloading bool in the Reload function but you are not checking the isReloading bool when shooting. It doesn't matter if you are reloading or not, the Shoot function only checks if there is ammo in the clip. Change the code on line 119 to if(ammoInClip != 0 && !isReloading). It might be even better to already check it at the update function, so the shoot function doesn't even execute.
In the update function you have the line: if (Input.GetButton("Fire1") && Time.time >=nextTimeToFire). This is not checking for reloading which it should.
Answer by $$anonymous$$ · May 02, 2019 at 05:15 PM
@metalted thank you for the help. And the update function if (Input.GetButton("Fire1") && Time.time >=nextTimeToFire) is for the fire rate.
Well yes, but i mean you could combine the boolean statement with this if statement, like this: if (Input.GetButton("Fire1") && Time.time >=nextTimeToFire && !isReloading){ Shoot(); }
Your answer
Follow this Question
Related Questions
How to change the damage my gun does? 1 Answer
How to add fireRate to my gun script? (Need Help) 1 Answer
Need help with burst fire script / adjusting the amount of damage my gun does. 0 Answers
Multi-gun Aiming System 1 Answer
How would I make text change size on mouse hover/end,How do I make text change size on mouse hover? 1 Answer