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.

Your recursion is getting into an infinite loop thats why your Unity is crashing at runTime… You can do two things -

  1. 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());
     }
     }
    
  2. Just make sure that your function does not go into an infinite loop by making if conditions