Uncontrollable platform spawning.

I made simple spawner like this:

void Update() {

    if (PlatformPosition.spawnNewPlatform) {
        NewPlatform();
    }
}

public void NewPlatform() {

    if (active) {
        newTransform = transform;
        Instantiate(prefabs[Random.Range(0, prefabs.Length)], newTransform.position, Quaternion.identity);
    }
}

And so it looks like my platform script:

public static bool spawnNewPlatform = true;

void Awake() {
    spriteSize = GetComponent<SpriteRenderer>();
    offscreenX = (Screen.width / PixelPerfect.pixelsToUnit) / 2 + offset;
}

void Update () {

    pos = transform.position;
    posX = pos.x;

    if (posX <= -offscreenX) {

        spawnNewPlatform = true;
    }
    else {
        spawnNewPlatform = false;
    }
}

Now when I start the “game” the spawner create unexpected number of platforms. Sometimes it’s 2 clones sometimes it’s 10… I don’t understand what is the problem and how to fix it. Is it frame rate issue?

Because the spawning logic is in the Update. So, potentially at each frame, the game could instantiate a new one until a particular condition is met.

I think that you should block additional spawnings (with spawnNewPlatform = false;) into the NewPlatform() function.