Search Unity

  1. Unity 2018.3 is now released.
    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. We've updated our Terms of Service. Please read our blog post from Unity CTO and Co-Founder Joachim Ante here
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    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

    kmce25

    Joined:
    Sep 18, 2017
    Posts:
    215
    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,082
    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. }