Search Unity

  1. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Let us know a bit about your interests, and if you'd like to become more directly involved. Take our survey!
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  5. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

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

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

  1. kmce25


    Sep 18, 2017
    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


    Dec 5, 2013
    Ideally you would keep track of which track you started playing.

    Code (CSharp):
    1. AudioClip currentClip;
    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. }
    7. bool AnyClipIsPlaying() {
    8.     for (int i = 0; i < ToySpawnLaugh.Length); i++){
    9.         if (ToySpawnLaugh[i].isPlaying) return true;
    10.     }
    11.     return false;
    12. }