Managing GameObjects

Ahad L. Amdani
May 16, 2021

--

Laser shots instantiating and being destroyed after reaching a certain threshold (off-screen)

When dealing with game objects, especially those that are spawned during the runtime of your gameplay, you’ll want to take care to ensure their proper instantiation as well as cleanup, so that your object graph doesn’t become overly cluttered and eat up heaps of memory. In the case of Sovereignty, the player’s ship will be able to utilize various projectile weapons, starting with the basic single-shot rapid-fire laser. The spawn of the laser prefab is triggered by user input, specifically the spacebar:

In the Player script, beyond tracking 2D movement input, we spawn a laser prefab with an offset from the ship.

When lasers are spawned, they are given a translation “forward” indefinitely, and once they’ve reached a certain threshold, are automatically cleaned up, as demonstrated here:

After reaching 8f further than anywhere the player can be on-screen, we know the laser is out of sight.

--

--