Search Unity

  1. Get all the Unite Berlin 2018 news on the blog.
    Dismiss Notice
  2. Unity 2018.2 has arrived! Read about it here.
    Dismiss Notice
  3. We're looking for your feedback on the platforms you use and how you use them. Let us know!
    Dismiss Notice
  4. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Learn more.
    Dismiss Notice
  6. ARCore is out of developer preview! Read about it here.
    Dismiss Notice
  7. Magic Leap’s Lumin SDK Technical Preview for Unity lets you get started creating content for Magic Leap One™. Find more information on our blog!
    Dismiss Notice
  8. 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 at 4:06 AM.

  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:
    15,376
    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. }