Updating the Shooting Logic

Let’s tweak the behaviour for shooting projectiles with the laser weapon.
Currently when a key is pressed, our weapon only shoots once. However I’d like to introduce a more fluent shooting logic so that if the player holds a key down, projectiles are being fired continuously.


Making the Player shoot for the entire duration a key is held and after each time a projectile has been fired, add a small delay.


  • A new GameObject “YourWeapon” attached to the Player GameObject.
  • Either a new script “Weapon” or the previous one we used, but now attached to “YourWeapon”.
  • A simple sprite texture for the Laser Projectile.

In case you are following along, make sure to remove the old Fire Projectile Logic from our player script. We will store the Logic on the Weapon that is attached to the Player, rather than on the Player itself.


It’d be more efficient to convert our shooting logic into a coroutine and not have it run persistently in the Update() function. We initialise a while loop and while condition is true the code is ran in which our FireProjectile() method is passed and a delay is added.


First we need to add a couple member variables. One that stores a reference to our Projectile Prefab, another one to initialise a custom Spawn Position for the projectile and another one that will define our delay between shooting projectiles.

Then assign a new Vector3(“your spawn position”) and run it in start depending on where you want to instantiate the projectile in game.

Our current FireProjectile() method;

Just to make sure it’s the Player that is pressing the key and to check if there is a Player at all let’s grab a reference to it which we can pass true or false in our next step.

Now let’s fabricate a Coroutine in which we call the function and add a delay each time it has ran the code block in the while condition is true loop. We can declare the fire delay outside of this routine by exposing it in the name.

_isFiring is for debugging purposes

At last we have to initialise the FireProjectileRoutine(float delay) in the Start() function. We can now pass in a value for our fire delay.

I think shooting is a lot more fluent now, by giving our weapon basic modular characteristics it’ll be slightly easier to modify it for different purposes in the future.


Previous | Next



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
Gert Coppens

Gert Coppens

Software Engineer — Unity Game and Application Developer