Instantiating and Destroying GameObjects in Unity (2D Space Shooter)

Marcus Ansley
2 min readMar 23, 2021

--

Implemented some instantiation and destruction code to the 2D Space Shooter project. Created a prefab for the laser, then wrote the code for instantiating and firing it upwards using Vector3.Up. I then came up to the matter of destroying it, and initially did this by using the while loop I created to run the movement logic (having it wait for a set number of seconds before breaking out of the loop and destroying the object):

I think I mostly did this because I tend to just prefer using coroutines to the Update method where I can. It tends to give me a better sense of control over the program, and I feel like I can clearly see exactly where I am and what’s running (and being able to halt the script’s logic is often quite handy). But in this particular case the idea of setting a lifespan is potentially redundant, given that we can just destroy the game object by providing a delay to the Destroy method (e.g. Destroy(gameObject, 5)).

I then just followed through with the module, and was reminded that it makes a lot more sense to just check when the object is roughly off screen and then destroy it. So instead I amended the original logic and removed the variables I was no longer using to end up with:

This way, the while loop logic can remain, only the condition is now based on the transform.position.y value. As long as the size of the camera and/or screen roughly remains the same I shouldn’t have any issues with this I imagine. There’s probably some more advanced logic out there to determine whether something’s no longer visible and destroy it based on that, so I think I’ll take a look into once I refine the project.

--

--