Search Unity

How to check if any audio is playing from an array, when chosen at random

Discussion in 'Scripting' started by ChuckieGreen, Aug 13, 2018.

  1. ChuckieGreen

    ChuckieGreen

    Joined:
    Sep 18, 2017
    Posts:
    358
    I have an array set up with 6 difference audio pieces attached. I want to make sure that no audio is playing before another one starts, but I cannot figure out how to check for it. This is the code I am using

    Code (CSharp):
    1. if(!ToySpawnLaugh[].isPlaying)
    2.         ToySpawnLaugh[Random.Range(0, ToySpawnLaugh.Length)].Play();
    The second line works perfectly, but it is what to place in the [], which I cant figure out. Either that, or I have chosen to do this the wrong way around. Anyone possibly know a way to set this up
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Ideally you would keep track of which track you started playing.

    Code (CSharp):
    1. AudioClip currentClip;
    2.  
    3. void Update() {
    4.     if(currentClip != null && !currentClip.isPlaying){
    5.         currentClip = ToySpawnLaugh[Random.Range(0, ToySpawnLaugh.Length)];
    6.         currentClip.Play();
    7.     }
    8. }
    If you really must check all clips, you can iterate through the array like this:

    Code (CSharp):
    1. void Update() {
    2.     if(AnyClipIsPlaying()){
    3.         ToySpawnLaugh[Random.Range(0, ToySpawnLaugh.Length)].Play();
    4.     }
    5. }
    6.  
    7. bool AnyClipIsPlaying() {
    8.     for (int i = 0; i < ToySpawnLaugh.Length); i++){
    9.         if (ToySpawnLaugh[i].isPlaying) return true;
    10.     }
    11.     return false;
    12. }