Trouble running a while loop

I’m trying to have my audio finish playing before moving on till the next lines, but I want movement, etc to still be running.

My code isn’t in an update function.

Thread doesn’t work
(“IsObjectMonoBehaviour can only be called from the main thread.”)

    void scriptTimer()
    {
        StartCoroutine(delayScriptAudio(a, b, 3));
        Thread.Sleep(100); // wait untill it detects audio playing
        while(source.isPlaying)
        {
return
        }

And the coroutine version didn’t work because it stops every other update function from running

    IEnumerable scriptTimer()
    {
        StartCoroutine(delayScriptAudio(a, b, 3));
        yield return new WaitForSeconds(1);
        while (source.isPlaying)
        {
return
        }

Would something like this be closer?

IEnumerator PlayAndThenDoStuff(AudioSource source)
{
    source.Play();

    while(source.isPlaying)
    {
        yield return null;
    }

    // DoStuff
}

So, yes. That is what i have tried the delayScriptAudio variable is just starting the audio. but the problem is that the while loop stops everything else untill its done. for example stops movement

Ok, I have found a work-around

yield return new WaitForSeconds(source.clip.length);

That is not what you have tried. Your while loop does not include a yield statement. In fact, yours never loops. It just returns on the first iteration. Also, delayAudioScript in your code is not a variable. It is a method (unless, maybe, it is a delegate, but you never listed that part of your code).

I’m glad you found a solution, but I also suggest you study coroutines a bit more, as perhaps there’s more you can do with them that you have achieved so far.

Stevens

Hey, sorry first time posting. I was just trying to summarize it, thus not including everything

    IEnumerator delayScriptAudio(int delay, int textNum , int audioSeq )
    {
        // wait for delay (seconds)
        yield return new WaitForSeconds(delay);
        // Text set to quote
        //textMesh.SetText(textQuotes[textNum]);
        // Get audio Source
        source.clip = audioArray[audioSeq];
        // Play audio
        source.Play();
       
    }
    IEnumerator scriptTimer()
    {

        //First Play sequance //4
        for (int i = 0; i < 4; i++)
        {
           
            StartCoroutine(delayScriptAudio(a, b, c));
            yield return new WaitForSeconds(source.clip.length);
            b++;
            c++;
        }


    }

Thank you for help, I will learn more. :slight_smile: