For loop not working

I’m making a game in C#, and the key concept of the game is instantiating platforms vertically. In one of my scripts for managing the instantiation of platforms, I have a for statement that will instantiate 4 initial platforms and the recycling of platforms is done in another script.

	public Transform platPrefabBottom;
	public Transform platPrefabTop;
	List<Transform> prefabList = new List<Transform>();
	int prefabIndex = 1;

	public static int platInstNum = 0;

	// Use this for initialization
	void Start () {
		prefabList.Add(platPrefabBottom);
		prefabList.Add(platPrefabTop);

		for(int i = 0; i < 4; i++)
		{
			Instantiate(prefabList[prefabIndex], new Vector3(0, platInstNum, 0), Quaternion.identity);
			platInstNum = platInstNum + 6;

			if(prefabIndex == 1)
			{
				prefabIndex++;
			}
			else if(prefabIndex == 2)
			{
				prefabIndex = 1;
			}

			print ("done: " + prefabIndex);
		}
	}

As you can see, I have a for statement that is supposed to loop 4 times, but instead only runs through once. I have told the code to print “done” for confirmation, and it only prints once.

Not sure why this is happening, could anyone give me some help? Thanks

Ok so your prefab list has only two elements, the index of the first is 0, and the second element’s index is 1, the problem is that you let your “prefabIndex” to reach the value of 2, which it’s outside of your list’s boundaries, therefore you probably get an error when you try to acces prefabList[2].

This is the correct code:

public Transform platPrefabBottom;
	public Transform platPrefabTop;
	List<Transform> prefabList = new List<Transform>();
	int prefabIndex = 1;   
	
	public static int platInstNum = 0;
	
	// Use this for initialization
	void Start () {
		prefabList.Add(platPrefabBottom);
		prefabList.Add(platPrefabTop);
		
		for(int i = 0; i < 4; i++)
		{
			Instantiate(prefabList[prefabIndex], new Vector3(0, platInstNum, 0), Quaternion.identity);
			platInstNum = platInstNum + 6;

			// This is correct.
			prefabIndex ++;
			if(prefabIndex >= prefabList.Count) {
				prefabIndex = 0;
			}
			
			print ("done: " + prefabIndex);
		}
	}