How can I Get An Audio Clip to Play a Certain Number Of Times C#

I’m trying to figure out how to make an audio file loop for a specified amount of times using C# is there a recommended way of doing this?

Hi,

try something like the following. Your GameObject needs a AudioSource attached.

public AudioClip impact;

void OnMouseDown()
{
    StartCoroutine(PlayAudio (3));
}

IEnumerator PlayAudio(int times)
{
	for(int i=0; i<times; i++)
	{
		audio.PlayOneShot(impact, 0.7F);
		yield return new WaitForSeconds(impact.length);
	}
}

You can use a counter for that.

Psuedo-code:

int counter = 0;
int maxCounterValue = 5;

void Update() or even a Coroutine() {
    if(counter < maxCounterValue)
    {
        if(!audio.IsPlaying())
        {
            audio.Play();
            counter++;
        }
    }
}