how to play multiple looping sounds from the same object?

I have an object that I’d like to play several different looping sounds from. I’ve added two Audio Source components to the object, I’ve checked “Loop” in the inspector, and I’m doing this in the script:

audio.clip = BounceLoop;
audio.Play();
    
yield WaitForSeconds (5);
   
audio.clip = RollSound;
audio.Play();

This issue I’m having is that in some instances, I may want both sounds to be playing simultaneously but switching the clip and using audio.Play() doesn’t allow for that. Is there another way to play a looping sound from script? All audio.loop = true does is set a clip to be looping.

Any ideas? I’m stuck!

2 Answers

2

Using Component.audio only returns one of your two audioSources! Instead, make an array of AudioSource objects, and assign them manually in the inspector, and then iterate through the array and do the same operation on each of them whenever you want to change something. Using the automatic component lookup assumes that you will only ever have one of each kind of component on your gameobjects, which in this case is obviously not true!

@syclamoth Hi, I'm a bit late, but I wanted to ask how can you assign the 2 audioSources through code, since I need to assign them dynamically because of scene reloads. When I try to follow what other people suggest (making an array and assigning them like shown below) I get the same audio source repeated: myAudioSource[0] = _musicManager.GetComponent"AudioSource"(); myAudioSource[1] = _musicManager.GetComponent"AudioSource"(); PS: I put AudioSource in quotation marks because it doesn't let me use the greater and less than signs for some reasons (in the code it's written properly)

–

To play at same time use audio.PlayOneShot()

PlayOneShot() doesn't inherit the looping properties of the clip from the audio source component and I haven't been able to find a way to make something loop from script. Does anyone have any other ideas?

–