Implementing Bullet Functionality in a 2D Shmup

David Hunter Thornton
3 min readAug 13, 2022

--

How do I delete an object after its spawned?

Objective: Explain how to destroy instantiated objects once off-screen.

We’ve covered a lot of topics in my previous articles and we’re gonna start by implementing some of those previous lessons. If you’ve missed them, a couple of important ones can be found here, here, and here.

The first thing I want to do is give my Bullet Prefab a “BulletLogic” Script.

Now, let’s make it move upward when fired.

And add our private speed variable with a “SerializeField”.

I know I blazed through those bits. But they’ve been covered in previous articles and we have new things to talk about!

With all of that done, we have bullets that shoot and travel away from our Player Character. However, as you can see on the right below, they survive forever and just keep going.

Now we can either destroy the Bullet (which is a game object prefab) when it reaches a certain distance or after a certain amount of time. For arguments sake, I’m going to show you both.

We’ve already talked about checking to see when an object leaves the boundaries of the scene here. We just need to add our “Destroy(gameObject)”

If you wanted to add a time delay, all that’s needed is this:

This creates a 4 second delay after the trigger in our “if” statement.

Another problem we’re having, is the bullet spawns on top of the Player Character before moving forward. So let’s get it to Instantiate just in front of the player by adding a little off set to our previous code.

In the above I’ve gone back to my CharacterController Script, found where I coded the Instantiate for my bullet, and then simply added the distance away that I wanted the bullet to spawn. I used the “new Vector3(0, 0, 0)” which was discussed in a previous article.

A lot of repeat stuff in this article, but in the next article we’re going to break down inputting a button delay on our fire rate.

Friendly Reminder: Don’t forget to keep updating your project through GitHub/Git and saving any changes you make to a separate branch. You can check out my other articles to get a breakdown of those steps! Day 1–9

--

--