Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved InvokeRepeating a random audio clip every x seconds

Discussion in 'Scripting' started by theMasky, Oct 5, 2020.

  1. theMasky

    theMasky

    Joined:
    May 8, 2015
    Posts:
    124
    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:
    Code (CSharp):
    1. void Update(){
    2.  
    3.             InvokeRepeating("MakeSound", 1f, 4f);
    4. }
    5.  
    6. //The method I'm calling on Update
    7. void MakeSound() {
    8.  
    9.         _audioSource.clip = gruntSounds[Random.Range(0, gruntSounds.Length)];
    10.         _audioSource.Play();
    11.  
    12. }
    I've tried doing something like:
    Code (CSharp):
    1. void MakeSound() {
    2.  
    3.         _audioSource.clip = gruntSounds[Random.Range(0, gruntSounds.Length)];
    4.         _audioSource.Play();
    5.  
    6.         var time = 3f;
    7.         if (_audioSource.clip.length == _audioSource.clip.length) {
    8.             Invoke("MakeSound", time);
    9.         }
    10. }
    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.
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    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.
     
  3. theMasky

    theMasky

    Joined:
    May 8, 2015
    Posts:
    124
    Ohhhh I see, sorry, I guess I didn't pay attention to that in the documentation. I'll try the three methods, many thanks!!