# 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?

• Have you made sure that the line of code runs only once? – Vadim Tatarnikov Aug 27 '15 at 18:59
• How is the position of the spawned platform determined? – realUser404 Dec 21 '16 at 9:49

As long as you only have one spawner, it doesn't look like the spawner could be instantiating 10 platforms. However, it's definitely possible that you'll get two. On the frame after the platform is instantiated, if Spawner.Update() gets called before Platform.Update(), then spawnNewPlatform will still be true and another one will get created.
Try setting spawnNewPlatform = false within Platform.Awake(). That way, when a platform is spawned, it will immediately prevent spawning of any other platforms.
Try adding if(spawnNewPlatform) return; to the top of your platform Update() method.
Also if it's a scrolling level and not a static single screen level then the platforms may be hitting the respawn point early. If that's the case you may want to use Camera.WorldToScreenPoint()
void Update() { Vector3 screenPos = camera.WorldToScreenPoint(target.position); Debug.Log("target is " + screenPos.x + " pixels from the left"); }