Day 7: Laser Code Cleanup!

Well, now that we’ve created lasers, let’s clean up the code we created!

GOAL: Clean up the code we created last time using Destroy(), a laser offset, and also implement a cool down functionality.

First and foremost, I don’t like that when we run the game and shoot a bunch of lasers, the lasers will just fly forever. This will seriously affect performance if we shoot a lot.

Too… many…lasers…

To fix this, we will use the Destroy component in our laser script to destroy the object once it hits a certain y-axis variable.

This piece of code will destroy the object if it flies higher than 8.0 on the y-axis. So now the objects should start to be destroyed shortly after shooting them, like so.

The lasers are added, and then quickly deleted.

I also don’t like how the laser seemingly spawns inside of the player. I would like to have it to where the laser spawns just in front of the player, just so it will look a lot cleaner when adding textures to this object. So, in our Player script, we want to add a new Vector3 to the laser spawn position that puts it just in front of the player.

This code sits inside our Instantiate method for the laser.

Results:

The lasers now spawn slightly in front of the player.

Now, I’d like to figure out a way to implement a cool down system, so the player can’t fire as fast as they can press the space bar. To do this, we’ll have to use Time.time and check against how long has passed in the game to keep from firing right away.

Results:

The lasers fire much slower.

Well, looks like we’ve created lasers to our liking now! They destroy themselves, fire slower, and are slightly in front of our player when spawned. Next time, we’ll take a look at creating the evil enemies you’ll be fighting! Until next time!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store