Fire limit and Ammo refill in Unity

The article here demonstrates putting a limit on the fire ability as well as refilling the out-of-stock ammo with a powerup.

The player object shall not fire more than 15 laser bullets at a stretch and hence all it needs is a few changes in the fire method already in place.

However, this shall be displayed somehow since backend numbers won’t make much sense to anyone playing the game.

Therefore, the first thing is to insert a UI element that should reflect the empty ammo state and when the player receives a powerup, the same element should change back to normal.

A cherry on the top would be a literal way of saying “No Ammo” which could be handled by adding a text element in UI stating the same line.

  • The process begins with finding out the image of choice for ammo.
  • Then, create a separate folder in your project to collect external images downloaded from internet sources.
  • Lastly and a critically important step is to convert the image to a “2D Sprite” texture to have it work with sprite-based components in the game.
  • Next, a text and an image UI element need to be deployed on the existing canvas with the placement of choice.

The plan is to one, change the color of the image when the player goes past 15 rounds of firing, and two, enable the “no ammo” text. (So before moving ahead, the text component of the text element should be disabled so that it could be enabled at a right time.)

  • Declare a variable that’d behave as a counter to check the fire calls.
private int _totalLaserFired = 0;
  • Use that variable to restrict the fire only when the count is less than 15.
  • In order to change the color of the image as well as enable the text component of the text element, we need to get access to both elements.
private GameObject AmmoPrefab;
private Text _noAmmoText;
  • Drop the image & text elements from the canvas to the player’s serialized fields.
  • The following code shall make perfect sense now.

The next part of the exercise is to swap a powerup routine that is going to refill the empty bucket of ammo.

To implement it, again one needs the powerup image of choice. Here, I have used the same image with a different color.

  • Declare a serialized field in the spawn manager script and assign the prefab that you’d like to behave as a powerup for ammo.
  • Create a method that reverts the color of the UI image back to normal and disables the text component of the text element.
  • Also, not to forget to bring back the fire counter to 0 the moment an ammo refill gets collected so that the player gets to fire 15 fresh rounds.
  • In the powerup script, add the third case statement which is going to trigger the associated method when the player will collect it.

Below is the final result :)

Thank you very much

Work in Progress.