Help with coroutine crashing unity
I have code to play music for my game. It all works until it tries to reset itself. For some reason Unity crashes whenever it tries to do this.
IEnumerator MusicPlayer()
{
Debug.Log("Start");
if (PlayedAllSongs())
{
Debug.Log("True");
int Repeat = 0;
while (Repeat >= Played.Length)
{
Played[Repeat] = false;
Repeat += 1;
}
}
Debug.Log("Checked");
do
{
Chosen = Random.Range(0, Songs.Length);
Debug.Log(Chosen);
} while (Played[Chosen]);
Debug.Log("Chosen");
Played[Chosen] = true;
Audio.clip = Songs[Chosen];
Audio.Play();
yield return new WaitForSeconds(Audio.clip.length);
Audio.Play();
yield return new WaitForSeconds(Audio.clip.length + 0.3f);
Debug.Log("Finished");
StartCoroutine("MusicPlayer");
}
private bool PlayedAllSongs()
{
Debug.Log("Called");
foreach (bool b in Played)
{
if (!b)
{
return false;
}
}
Debug.Log("true");
return true;
}
Any help would be greatly appreciated, thank you.
Comment
Best Answer
Answer by Hellium · May 18, 2019 at 06:58 AM
I would have reworked your code as follow:
IEnumerator MusicPlayer()
{
List<AudioClip> remainingAudioClips = new List<AudioClip>();
while( true )
{
remainingAudioClips.AddRange( Songs );
while( remainingAudioClips.Count > 0 )
{
int songIndex = Random.Range( 0, remainingAudioClips.Count );
Audio.clip = remainingAudioClips[songIndex];
Audio.Play();
yield return new WaitForSeconds(Audio.clip.length);
Audio.Play();
yield return new WaitForSeconds(Audio.clip.length + 0.3f);
remainingAudioClips.RemoveAt( songIndex ) ;
}
}
}
You can get rid of Chosen
and Played
variables.
Your answer
Follow this Question
Related Questions
Boolean, IEnumerator and SetActive probleme.BUG 2 Answers
How to erase message after 3 seconds 1 Answer
Calling a bool from another script doesn't seem to be working 1 Answer
Coroutine Not Starting - Crashes Instead? 1 Answer
Destroy Problem 2 Answers