Prefab instantiation and destruction

Hello,

I’m pretty new to Unity and even though I started to read the doc and some books, I still have questions I don’t find an answer for.

So, let say I want to throw rockets on a wall when I hit a key, I would write a script to instantiate prefab and throw the prefab on my wall.

My question is : is there anything special that occurs when my rocket that miss the wall goes out of the scene or do I still have to find a way to destroy it otherwise it will leak?

Also, maybe I should have find this in the documentation so if someone can point it out to me, I’ll gladly read it.

Thank you

If you don’t do anything about it, it’s going to exist as long as your scene does. If there is one or two, that’s not a huge problem, if you have a couple thousand, you’re in trouble ! So, a common trick to do that, create an empty game object in the middle of your scene with a box collider so big it contain everything, set to trigger. Add a script that destroy everything that comes out of it (OnTriggerExit), and pray for those poor souls. That should do it :slight_smile:

Yes, objects continue to remain in memory until you won’t call function Destroy() on them.

As an example, I’ve recently made an arcade shoot 'em up, so I attached this script to my projectiles:

function Start(){
   yield WaitForSeconds(5);
   Destroy(gameObject);
}

With that, my projectiles free the memory 5 seconds after their creation. In fact, after such a time, they already hit an enemy, or they are already out from the field of view. I don’t want to have thousands on them occupying memory and CPU!

When this implementation isn’t possible (or nice), you can have invisible walls, surrounding the perimeter of the scene, and make some objects destroy themselves whenever they hit these walls.

Is not clear, from your question, if this was your only doubt, or you are also asking about instantiating a prefab when pressing a key (I don’t know if that was a premise for what I’ve just said, or a question itself).

Thank you for all of your answers.

@BiG I’m fine with the instantiation of the rockets.

Those solutions are good for me, either use a yield, the second param of destroy or an invisible wall that will destroy on collisions.

It’s not really an advanced topic but when I’m reading all the examples on how to instantiate a rocket, they never destroy the instances and they fall out somewhere in the void under my scene. I was simply worried about memory.

Francis