- Home /
Making a continuous shooting sound while the fire button is held down.
Hey fellas, making an fps game with my buddy for a programming class. I wanted to add a sound to when the gun is firing and it is sort of working right now and the sound plays if you tap the shooting button but when you hold down the firing key it only plays after you release the fire button. Was just wondering if you guys could help me out Thanks.
Heres the code
using UnityEngine;
public class GunScript : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public float fireDelta = 0.5f;
private float nextFire = 0.5f;
private float myTime = 0.0f;
private AudioSource mAudioSrc;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
void Start()
{
mAudioSrc = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
myTime = myTime + Time.deltaTime;
if (Input.GetButton("Fire1") && myTime > nextFire)
{
nextFire = myTime + fireDelta;
Shoot();
}
}
void Shoot ()
{
muzzleFlash.Play();
mAudioSrc.Play();
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
}
}
}
Answer by georgeq · Jan 17, 2020 at 05:14 AM
In the way you're handling it, if Shoot is called and the audio clip hasn't finished playing yet, it get reset. You need to decouple the sound from the shoot method. The easiest but perhaps the less efficient way to do it, would be to create a prefab with just an audio source that plays the clip on awake, and a small script to destroy the instance after the clip has finished, then, on the shoot method instead of playing the sound directly, create an instance of such prefab. A better solution would be to create an array of audio sources, and on the Shoot method, loop over to find one which is not busy playing at that moment, and play it.
Thank you for the response and explanation. I'll be sure to use this in other projects if I come across the same problem but for now I fixed it using a less sophisticated solution by creating a new object that plays the sound whenever I shoot.
Your answer
Follow this Question
Related Questions
How to add sound to gun shot script 4 Answers
Gun Shooting Animation Won't Play 0 Answers
How to Network Sound? 1 Answer
FPS, Trying to add sound to footsteps, Not working! 2 Answers
fps shooting enemy 1 Answer