ntrch
ntrch

Reputation: 96

Play sound while button is held down

I have a 1.5 seconds audio file - a single gunshot sound. I want to be able to play the sound while the mouse is pressed (like an automatic weapon), and I used InvokeRepeating to call the shoot method, with a very low repeatRate:

if (Input.GetButtonDown("Fire1"))
{
    InvokeRepeating("Shoot", 0f, 1f/currentWeapon.fireRate);
} else if (Input.GetButtonUp("Fire1"))
{
    CancelInvoke("Shoot");
}

And this is the Shoot method:

void Shoot()
{
    shootSound.PlayOneShot(shoot);
}

The problem is the sound cuts off and the shot can't be heard, it's playing for a fraction of a second instead of the whole audio clip. I tried play() and playOneShot().

Is there an option to play each clip to its fullest separately, like creating clones of it?

Thanks!

Upvotes: 2

Views: 1575

Answers (2)

ntrch
ntrch

Reputation: 96

I solved it, I used an empty GameObject with an AudioSource, and instantiated a copy of it in each Shoot method:

GameObject gunObj = Instantiate(gunObject);
Destroy(gunObj, 1f);

Works perfectly now!

Upvotes: 0

Programmer
Programmer

Reputation: 125245

Most things in your code are just unnecessary. You don't need InvokeRepeating for this. Since you want to continue to player sound(shooting effect) while the button is held down, Input.GetButton should be used instead of Input.GetButtonDown because Input.GetButton is true every frame the button is held down and is made for things like auto fire.

A simple timer with Time.time should also be used to determine the rate to play the sound then play the sound with the PlayOneShot function.

This is what that should look like:

public float playRate = 1;
private float nextPlayTime = 0;

public AudioSource shootSound;
public AudioClip shoot;


void Update()
{
    if (Input.GetButton("Fire1") && (Time.time > nextPlayTime))
    {
        Debug.Log("Played");
        nextPlayTime = Time.time + playRate;
        shootSound.PlayOneShot(shoot);
    }
}

The playRate variable is set to 1 which means 1 sound per-sec. You can use this variable to control the play rate. Lower it to play many sounds. The value of 0.1f seems to be fine but it depends on the sound.

Upvotes: 2

Related Questions