- Home /
Music player giving indexoutofbounds error
I'm developing a game that uses the music player from http://answers.unity3d.com/questions/652919/music-player-get-songs-from-directory.html (the best answer in c# it's what i'm using)
It's great, but in my app, i don't have a play button on the gui. I want the music to start right away after the "ReloadSounds()" function ends. So, I call the "PlayCurrent();" at the last line of the "ReloadSounds()" function.
The problem is sometimes i get a indexoutofbounds error and it's because the List clips attribute is empty when i call playcurrent()
Strangely, there's no problem if i keep the calls to print(); on the function LoadFile(string path) (there are 2 prints on this function, like the example on the link).
I think the error is cause because i start coroutines and i think coroutines in unity are like threads, but people say they're not and that i shouldn't worry about thread-safety when i use them.
Is there any way to make my app work without relying on print() calls on the LoadFile(string path) function? Is coroutine a thread on unity?
Answer by Eno-Khaon · Jul 06, 2016 at 05:52 PM
In that script, the files are specifically being loaded using a coroutine in order to avoid any major performance impact, should the file loading process take longer than expected.
What you're currently facing is effectively a race condition. Will the file be done loading first or will you try to play it first?
Fortunately, there's a relatively easy way to deal with this:
First, rather than trying to play the audio immediately after starting the coroutine StartCoroutine(LoadFile(s.FullName))
, you can do something like check whether the List<> is currently empty before adding the file at the end of LoadFile() and, if so, begin playing it. Or, alternatively, you could simply check whether the audiosource is already playing anything first.
Again, either of these options would occur at the end of LoadFile() rather than at the end of ReloadSounds() because there's no guarantee when using the coroutine that the file will actually be ready in time.
Your answer
![](https://koobas.hobune.stream/wayback/20220612084330im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Is it possible to modify the Audio of a complete Unity project downloaded from the Asset Store? 1 Answer
Debug Editor crashes (Possible sound related ???) 3 Answers
.wav file not working 2 Answers
audio change object size 1 Answer
Audio Scripting 1 Answer