Unity3d Foundations: Creating & Destroying Game Objects

Marc Hewitt
2 min readMay 4, 2021

--

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

All you need is one line of code to spawn something in.

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

Destroying something takes even less code.

Destroy( gameObject );

BUT
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

Creating and destroying objects can be costly. Especially if you have 100 enemies each firing off a projectile every second! Still Unity3d and modern hardware make the above basics just fine for small arcade games or minigames.

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.

--

--

Marc Hewitt
Marc Hewitt

Written by Marc Hewitt

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

No responses yet