3
\$\begingroup\$

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?

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

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.

\$\endgroup\$
0
\$\begingroup\$

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"); }

This will convert the world coordinates to those matching your screen so that you can check when they're out of sight.

Link to help: https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.