How do i fix this infinite loop?

I am new in C# and Unity, I would love an explanation of the issue but simple fix would be just fine. Thank you.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moveT : MonoBehaviour {

    public GameObject treeFab;                                 //The tree game object.
    public int treePoolSize;                           //How many trees to keep on standby.
                                                              //How quickly trees spawn.
   
    private GameObject[] trees;                                   //Collection of pooled trees.
                                                                
    private Vector3[] pos1rot1;                        //Collection of pooled Positions.

   

   
    void Start ()
    {
        
        trees = new GameObject[treePoolSize];
        pos1rot1 = new Vector3[5] ;
        int i;
        for (i = 0; i < 5; i++)
       
            pos1rot1[i] = new Vector3 (-123+10*i, 27-i, 74+3*i);

       
       
        for ( i = 0; i < treePoolSize; i++)
        {
           
            trees[i] = (GameObject)Instantiate(treeFab, pos1rot1[i % 5], Quaternion.identity);

        }
           
                      
           
       
    }
   
    private int index = 0;
   
    void Update ()
    {
        if (gameControl.instance.gameState == 1 && (trees[index].transform.position.z < -13f))
        {
           
            trees[index].transform.position = pos1rot1[Random.Range(0,5)];
            index++;
        }
        if (index >= treePoolSize)
            index = 0;

    }
}

I don’t see any code there that could cause an infinite loop. I see some weird concepts going on (why are you setting the position in Update’s, after they are spawned?), but no infinite loop potential. It’s possible that Start() could take a long time if your treePoolSize is really big, but not to the point of freezing Unity.

I can think of 2 possibilities:

  1. It’s another script entirely that’s causing the infinite loop.
  2. This script is on the prefab that’s being instantiated. So this script generates a tree, which has this script, which generates a tree, which has this script, which…
1 Like
  1. This script is on the prefab that’s being instantiated. So this script generates a tree, which has this script, which generates a tree, which has this script, which…

That was the problem, thanks a lot man:)

This will eat whole performance. Forget this way.

The guy just trying to learn the very basics, he can worry about that much… much later.