Instantiating and destroying (Game Dev Day 8)

Every time you kill and enemy, pick up an item, or simply shoot a gun in a video game you are utilizing the instantiate or destroy commands in C#.

Instantiate is just a fancy word for create from reference. This command will summon a pre-created object or effect when linked properly

Every laser and enemy destroyed is using one of these commands.

So what does that look like for us in our 2D environment?

We instantiated the “Lasers” from our player object (blue).

So what does this look like in C#?

First things first is creating the laser object and attaching a C# script to it. My laser is a simple capsule preset from Unity that I turned red. The script utilizes a transform.translate command to move the laser up the screen!

When using instantiate, you have to place the command on the object you want to “spawn” your projectile. So in this case, we place the command on the “Player” to create the “Laser” objects at their position.

How we shoot our laser.

This line of code simply says to create our laser prefab (our laser object) at our current position + a slight offset on the Y axis. Without the offset the “laser” would spawn at our (0,0,0) and would clip out of us.

With this in place we can fire our new “Lasers”, though they serve no function at this time. We need to add some Destroy commands to our code to make both our enemies and our weapons dangerous to the opposing side.

When calculating damage, the objects in question need to have triggers and at least one of the objects in the exchange MUST have an Rigidbody attached.

Our enemy, now with a Rigidbody (Make sure you turn off Use Gravity).

So let make a system where if a laser hits an enemy, the enemy is destroyed.

Deadly Lasers!

Unity has some built in functionality here that will assist us greatly. We are going to us the following void to set up our destruction parameters.

Destruction parameters.

From the top down, this void is saying a few things;

  1. If I hit the player, the player loses a variable labeled “Lives” (We will cover this in detail later)
  2. I get destroyed
  3. If I hit a laser, the laser is destroyed
  4. I get destroyed.

It’s important that the enemy object is the last thing in the script, because once it is destroyed it will not continue the code past its destruction.

To get all these objects playing nicely, we are going to create Tags for them in Unity. The Player is a default tag, but we will have to make the Laser and Enemy tag.

Location for tags on the editor. Names can be anything so long as they match in the C# script.

With all this input, we now have a system for destroying our enemy objects with our lasers!

Unity Developer