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
So what does that look like for us in our 2D environment?
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.
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.
So let make a system where if a laser hits an enemy, the enemy is destroyed.
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.
From the top down, this void is saying a few things;
- If I hit the player, the player loses a variable labeled “Lives” (We will cover this in detail later)
- I get destroyed
- If I hit a laser, the laser is destroyed
- 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.
With all this input, we now have a system for destroying our enemy objects with our lasers!