Destroying objects after certain point

I have a 2d endless scroller game which uses 2 game objects, a generation point and generator that copies my platforms and places them infront of player when they are too far apart. However this leaves a trail of copies behind the player that are no longer needed. I can’t figure out how to remove them. I tried doing the same thing that i did with generating them except replacing Instantiate with destroy, as well as a few other things. All this did was destroy the first platform right away.

Any thoughts?

you can make time destroyer script

public float destroyTime;
void Start () {
Destroy (gameObject, destroyTime);
}

or off-screen destroyer script

void OnBecameInvisible () {
Destroy (gameObject);
}

or, i dont know, something else :smile:

add script to platform

1 Like

unless I’m doing something wrong neither options work. Also I don’t think I can bind the script to the platform because once the platform gets destroy the script would too right? wouldn’t it be simpler to bind the script to a gameobject then child it to the camera?

do you have platform prefab (or what do mean with “generator that copies my platforms”) ? If so, dont forget update your prefab if you have added script to it. I would make platform, then prefab of it. And then instantiate the prefabs (clones).

if your platforms have scripts on them that are moving them across screen then I’m assuming the scripts will all be the same no matter what size the platform is or the height it is on screen?
How are you spawning the platforms? Are you instantiating prefabs or have you built a really, really long scene with all the platforms already placed (which wouldn’t really be an endless runner since you could theoretically get to the end)?

Alternatively, if the pattern is to repeat itself you could set a trigger point that is offscreen & when the object hits it change its position so it is at the end of the line (of the ones in front of the player). You could randomise the height that it spawns at but you’d need to probably put it in a range from the one that is currently at the end of the line (the one that will end up in front of it) so you can ensure the player can actually reach it.

Was going to suggest something like Ted suggested.

An invisible collider/trigger past the player so when the platforms collide with it they get destroyed.