Music player giving indexoutofbounds error

I’m developing a game that uses the music player from Music player - (load sound files at runtime from directory, and play them) - Questions & Answers - Unity Discussions
(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?

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.