- Home /
Audio repeats
hello i am having a problem with my gun . When i shoot it the audio is being repeated when i click the shoot button rather than being continued. Please help
public enum GunType { Semi, Burst, Auto };
public GunType gunType;
public float rpm;
// Components
public Transform spawn;
private LineRenderer tracer;
// System:
private float secondsBetweenShots;
private float nextPossibleShootTime;
void Start() {
secondsBetweenShots = 60 / rpm;
if (GetComponent<LineRenderer>()) {
tracer = GetComponent<LineRenderer>();
}
}
public void Shoot() {
if (CanShoot())
{
Ray ray = new Ray(spawn.position, spawn.forward);
RaycastHit hit;
float shotDistance = 20;
if (Physics.Raycast(ray, out hit, shotDistance))
{
shotDistance = hit.distance;
}
nextPossibleShootTime = Time.time + secondsBetweenShots;
GetComponent<AudioSource>().Play();
if (tracer) {
StartCoroutine("RenderTracer", ray.direction * shotDistance);
}
}
}
public void ShootContinuous() {
if (gunType == GunType.Auto) {
Shoot ();
}
}
private bool CanShoot() {
bool canShoot = true;
if (Time.time < nextPossibleShootTime) {
canShoot = false;
}
return canShoot;
}
IEnumerator RenderTracer(Vector3 hitPoint) {
tracer.enabled = true;
tracer.SetPosition(0, spawn.position);
tracer.SetPosition(1, spawn.position + hitPoint);
yield return null;
tracer.enabled = false;
}
}
Answer by Sageose · Oct 20, 2016 at 02:44 PM
I'm not sure, but you might want to try
GetComponent<AudioSource>().PlayOneShot();
instead of
GetComponent<AudioSource>().Play();
If not, is the audio clip only one shot or is it a continuous shooting sound?
Answer by PeteD · Oct 20, 2016 at 02:44 PM
I'm not sure I understand what you mean by
When i shoot it the audio is being repeated when i click the shoot button rather than being continued.
this line
GetComponent().Play();
Will start the sound again from the beginning. To pause and resume the audio from it's current position you would need to enable and disable the audiosource instead of using play and stop.
i mean that when i click to shoot the audio is being replayed
Answer by Kharief · Oct 21, 2016 at 07:27 AM
i made a video about my problem here : https://www.youtube.com/watch?v=1NzSF33t8fs&feature=youtu.be
If all you want is to stop the audio restarting if it's already playing then something like the code below will work
AudioSource audio = GetComponent<AudioSource>();
if( ! audio.isPlaying )
{
audio.Play();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612095038im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
audio loop when I click the MouseButtonDown(0) 1 Answer
AudioHighPassFilter with multiple AudioSource 1 Answer
Global audio option 2 Answers
Audio loops too early 2 Answers
Playing Sound 2 Answers