Unity3d Foundations: Creating & Destroying Game Objects

Simple Spawn at Point and Destroy when off-screen

Creating and destroying objects is a fundamental concept in software development, but especially so in Game Development. So let’s run through the basics real quick and then a quick talk on performance.

Creating Objects at Runtime

Instantiate( gameObject, position, rotation );

What that looks like in the above Gif though is a bit more complex looking.

The laserPrefab is set up in the player class and assembled in Unity Inspector, as is the spawn point to shoot from. Then we wait for the player to hit Space before shooting, else we’d be shooting every frame!

Destroying Objects at Runtime

Destroy( gameObject );

It takes a bit more game logic to figure out “when” it should be destroyed.

For example:
Is it hitting something? Is it going off-screen? Did the player load a new level?

Then you need to decide if you’re simply destroying it or if you have any extra actions.
Such as adding an explosion effect.

explosionPrefab holds a VFX and SFX

Performance Concerns

Once you get into production VR, mobile, or optimizing massive scenes you will find you’ll need to learn more thAn the above to get the job done. Some solutions such as ObjectPooling are a good place to begin looking, where instead of creating/destroying you “Fake” destroy, stash the object on the side, then re-use it “as if new”. While it has some overhead it effectively reduces the performance cost enough to be a solid solution for many games.

An Austin TX Unity3d Developer with a unique background in marketing, design, & software development leading digital web agencies to success for the past decade