For loop breaks before 10 objects are created

public class PlatformSpawn : MonoBehaviour
{

	public bool platformMaxed = false;
	public static int platformSpawned;
	public GameObject PlatformPre;
	
	void Start () 
	{
		
	}
	
	public void PlatformSpawning()
	{
		while (platformMaxed == false)
		{
			for (platformSpawned = 0 ;platformSpawned <= 10; platformSpawned++)
			{
				Instantiate (PlatformPre, 
				new Vector3(Random.Range(-15,15),Random.Range(1,15),0),
				Quaternion.identity);
				platformSpawned++;
				//PlatformPre.collider.isTrigger = false;
				Debug.Log("Platform Spawned" + platformSpawned);
				
				if (platformSpawned >= 10)
					{
						platformMaxed = true;
						break;
					}
			}
			
			if (platformMaxed == true)
				break;
			
			
		}
			
	}
	
	
	void Update () 
	{
		if (platformSpawned <= 9)
		{
			PlatformSpawning();
		}	
	}
}

Public static int platformSpawned is connected to another script here:

void OnCollisionEnter(Collision other)
	{
		Debug.Log("CollisionDetected");
		
			if (other.collider.tag == "Platform")
			{
				Debug.Log("PlatformSpawned From Collision " + PlatformSpawn.platformSpawned);
				Destroy(Platforms);
				PlatformSpawn.platformSpawned--;
			}
	
		else
		{	
			return;
		}
	}

For some reason the Debug.Log says it stops at anywhere around 5-8 platforms in the PlatformSpawn.cs.

In the PlatformCollision.cs it goes in the negative value.

So the question is: Why do the platforms stop being created even though the if statement is not met?


You are incrementing platformSpawned twice each iteration, once explicitly in your code just after the instantiate, and then implicitly by the for loop. In addition you are calling the function again every frame. The new copies are likely resetting your static variable, and causing nastiness. Try removing the explicit increment, changing the spawning function into a coroutine, and calling it from your start function. Ala:

using System.Collections;

void Start()
{
    StartCoroutine(PlatformSpawning());
}

public IEnumerator PlatformSpawning()
{
    while (platformMaxed == false)
    {
        for (platformSpawned = 0; platformSpawned <= 10; platformSpawned++)
        {
            Instantiate(PlatformPre,
            new Vector3(Random.Range(-15, 15), Random.Range(1, 15), 0),
            Quaternion.identity);
            //PlatformPre.collider.isTrigger = false;
            Debug.Log("Platform Spawned" + platformSpawned);

            if (platformSpawned >= 10)
            {
                platformMaxed = true;
                break;
            }
        }

        if (platformMaxed == true)
            yield break;

        yield return 0;
    }
}