How to destroy an instantiated prefab object and keep instantiating it?

Hello, I’m woking on a game similar to Temple Run and I’m spawning (instantiating prefabs) all the platforms randomly to create the way for the run. After the player has passed a platform I need to destroy that platform but I don’t know how to do it… I tryed putting a box collider over the platform and attach to the platform a script with a OnTriggerExit void to destroy the platform when the player exit the trigger… but then I get an error that says:

I searched a lot in the forum and with Google for a solution but I didn’t find anything… any help would be highly appreciated. Thanks

Its probably because Destroy happens on the next frame just try adding a:

if(theGameObject != null)
{
    //Destroy
}

Better way in my opinion would be to create garbage collector. A empty game object outside camera view where his only job is to delete all objects that enter trigger.

Also I would suggest You consider object pooling as instantiate is very process heavy and each object destroy calls Unity garbage collector that need to free up memory and then memory need to be allocated again when object is creates. It is not such big bottle neck on PCs (it can depending on model complexity and textures) but if Your game is for mobiles it can tank FPS.

2 Likes

Hi, thanks for your help, I already tryed it and it doesn’t work

Hi

Hi, thanks for your reply, I don’t understand where should I put this empty game object… as the platforms are instantiated on the z and x and y axis (in a random way) and the player run over them… I can put a trigger on the player or a trigger on the instantiated platforms only… Am I missing something?
About object pooling I’m giving it a try… thanks for the hint

What you would usually use in this kinds of games that have lots of same objects you would create object pool for the amount of objects visible on screen and + little buffer.

And when player passes that object you just move it to new location. This way you don’t waste resources and reuse objects.

This is just in base how it should work of course usually its a bit more complicated you would maintain different pools for different objects or change objects when moving them to new location if that is your game logic etc. But base is keep a pool of objects and reuse them.

1 Like

I’ve resolved all my problems with object pooling… thanks a lot bro!

1 Like

Yeah, it worked very well for my case… thx!