- Home /
Question by
Ngoadam123 · Jun 29, 2014 at 01:42 AM ·
reload
Gun script Reload not working well
I made this gun script and I tried making a reload but when I reload the spare ammo goes to the negatives and the sound is distorted, any help?
#pragma strict
var GunShot : AudioClip;
var ReloadSound : AudioClip;
var bullets : int;
var maxBullets : int;
var spareBullets : int;
var reloadTime : float = 1.5;
var fireRate : float = 1.5;
var damage : float = 1.5;
var force : float = 250.0;
var distance : float;
var maxDistance : float = 1.5;
private var nextFire : float = 0.0;
function Update() {
if(Input.GetButton("Attack") && bullets > 0 && Time.time > nextFire) {
audio.PlayOneShot(GunShot);
nextFire = Time.time + fireRate;
bullets -= 1;
{
var hit : RaycastHit;
if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), hit))
Debug.DrawLine (transform.position, hit.point, Color.blue, 1);
{
distance = hit.distance;
if(distance < maxDistance)
{
hit.transform.SendMessage("Damaged", damage, SendMessageOptions.DontRequireReceiver);
hit.rigidbody.AddForceAtPosition(transform.forward * force, hit.point);
}
}
}
}
if(Input.GetButton("Reload") && bullets < maxBullets) {
bullets = 0;
Reload();
}
}
function Reload() {
yield WaitForSeconds(reloadTime);
audio.PlayOneShot(ReloadSound);
spareBullets -= maxBullets;
if(spareBullets > 0)
bullets = maxBullets;
}
Comment
Answer by Juice-Tin · Jun 29, 2014 at 01:53 AM
Not sure why audio is distorted, but this should fix the reload if you have only a few spare bullets left.
if(spareBullets < maxBullets){
bullets = spareBullets;
spareBullets = 0;
}
else{
spareBullets -= maxBullets;
bullets = maxBullets;
}