- Home /
A simple recursion leads to crash
Hi foks, I've got a little problem:
I've got an array that is filled with lists. The list variates in size. And I got a function that needs to walk trough all the entries of this lists and then jump to the next list entry (that could be zero as well.)
I made a short little script but every time I want to execute it unity crashes, and I don't know why.
Here is an exampe of my code:
private int Speedlevel = 0;
private int Speedlevelindex = 0;
public GameObject aktiveFigur;
private List<GameObject>[] Zugreihenfolge = new List<GameObject>[5];
private void Reihenfolge(){
if(Zugreihenfolge[Speedlevel].Count>0 && Speedlevelindex<Zugreihenfolge[Speedlevel].Count){
aktiveFigur = Zugreihenfolge[Speedlevel][Speedlevelindex];
Speedlevelindex++;
Kampfrunde();
return;
}else{
Speedlevel++;
Speedlevelindex = 0;
if(Speedlevel>4){
Speedlevel = 0;
}
Reihenfolge();
}
}
private void Kampfrunde(){
if(aktiveFigur.GetComponent<Figur>().KI=true){
print ("Hello World" + aktiveFigur.name);
Reihenfolge();
}
}
Thanks for any help and good night.
Where do you initialize the Array? You don't check for Zugreihenfolge[Speedlevel]==null, are you sure all are filled? What do you mean with crashes? Can you step through the script and see where it crashes?
The way it's written, it will loop infinitely (having Unity hang up forever). Every branch leads to Reihenfolge() being called again. You need to have an exit condition somewhere.
Answer by Imankit · Jan 03, 2014 at 06:39 AM
Your recursion is getting into an infinite loop thats why your Unity is crashing at runTime.. You can do two things -
Make the function IEnumerator and give a wait of 0.034f sec before calling the function in else -
private IEnumerator Reihenfolge(){ if(Zugreihenfolge[Speedlevel].Count>0 && Speedlevelindex<Zugreihenfolge[Speedlevel].Count){ aktiveFigur = Zugreihenfolge[Speedlevel][Speedlevelindex]; Speedlevelindex++; Kampfrunde(); return; }else{ Speedlevel++; Speedlevelindex = 0; if(Speedlevel>4){ Speedlevel = 0; } yield return new WaitForSeconds(0.034f); StartCoroutine(Reihenfolge()); } }
Just make sure that your function does not go into an infinite loop by making if conditions
Thank you very much, that line yield return new WaitForSeconds(0.034f); worked out perfectly. I tried it yesterday with a coroutine and added the line just to skip one frame, but this how ever didn't work. Why does it work with this specific time?
Any way, thanks again =)
0.034 seconds is close to 30fps ... Butt it's not a good idea to skip with time values if you want to skip to the next frame. This time value will skip two frames on most systems anyway.... To skip just one frame do this:
yield return null;
Thank you for this. I have done a lot of searches for the solution to these infinite loops and this is the only one that explains it so simply.