Hello! I have a problem. My automatic weapon fires way too fast and whenever it shoots the sound doesnt finish. It’s like "ba-ba-ba-ba-ba-ba-ba-bang (bang is when I let go of left mosue button)
I don’t know how to fix this so any help would be appreciated.
Here is my code:
function Update () { if (Input.GetButton("Fire1")) { var gunsound : AudioSource = GetComponent.<AudioSource>(); gunsound.Play(); GetComponent.<Animation>().Play("MachineGin_shoot"); GlobalAmmo.CurrentAmmo -= 1; } }
There’s two ways to go about this. If you simply want to let the audio play you can say this
function PlayGunSound()
{
if (gunsound.isPlaying) return;
gunsound.Play();
}
This will ensure that the full sound plays.
If you want to slow down the gun and be sure the full sound plays, you’ll need a timer.
Declare a two floats at the top like this
public var speed;
var timer;
In the Update function, say this
timer += Time.deltaTime;
Finally, when you fire the gun say this
if (Input.GetButton("Fire1") && timer >= speed)
{
PlayGunSound();
timer = 0;
}
In the editor, you can say how fast the gun is by setting the speed value.
UPDATE:
You have to use a line like this
var gunsound : AudioSource = GetComponent(AudioSource);
You can declare that at the top and it should get your audio source.
In the end, it could look something like this
#pragma strict
public var speed;
var timer;
var gunsound : AudioSource;
var anim : Animation;
function Start()
{
gunsound = GetComponent(AudioSource);
anim = GetComponent(Animation);
}
function PlayGunSound()
{
if (gunsound.isPlaying) return;
gunsound.Play();
anim.Play("MachineGin_shoot"); //Should that be MachineGun?
GlobalAmmo.CurrentAmmo--;
timer = 0;
}
function Update()
{
timer += Time.deltaTime;
if(Input.GetButton("Fire1") && timer >= speed)
PlayGunSound();
}
Set up a delay system. Something like:
var lastShot : float = 0;
var delay : float = 0.2f;
function Update() {
lastShot -= Time.deltaTime;
if(Input.GetButton("Fire1") && delay <= lastShot) {
//firing code
lastShot = delay;
}
}