InvokeRepeating a random audio clip every x seconds

I’m trying to write a code that plays a random sound every x seconds, however, when running, the code have a weird behavior. It starts “fine”, but after a few seconds, instead of first reproducing one clip, wait x seconds, and then play another clip, it just randomly plays a lot of sounds at the same time, without any delay between them.

Here’s my code so far:

void Update(){

            InvokeRepeating("MakeSound", 1f, 4f);
}

//The method I'm calling on Update
void MakeSound() {

        _audioSource.clip = gruntSounds[Random.Range(0, gruntSounds.Length)];
        _audioSource.Play();

}

I’ve tried doing something like:

void MakeSound() {

        _audioSource.clip = gruntSounds[Random.Range(0, gruntSounds.Length)];
        _audioSource.Play();

        var time = 3f;
        if (_audioSource.clip.length == _audioSource.clip.length) {
            Invoke("MakeSound", time);
        }
}

But it didn’t work, it gave me the same result.

I’ve also searched and I found a lot about other random cases, but nothing similar to mine.

InvokeRepeating only needs to be called once. You are creating a new repeating invoke every frame so if you really want to use that method, call it once in the Start or Awake methods. Personally, I would use a coroutine or timer myself.

Ohhhh I see, sorry, I guess I didn’t pay attention to that in the documentation. I’ll try the three methods, many thanks!!