Objective: Add ammo system with audio warnings to laser shots.
Limiting the number of laser shots the player can take requires an ammo system in the Player script. This system is controlled by the private int _ammo =15 variable. Using Audacity, record an audio file for low ammo warning and another for the no ammo warning, saving in a Unity compatible mp3 format. Assign these files to the AudioClip variables _powerLowClip and _powerDepletedClip using the Unity inspector.
Within the void FireWeapons() function in the Player script checks the ammo level and plays a warning by calling a coroutine, AudioWarning(), only if a warning is not already playing, i.e. _audioWarningOn is false. The exception is that when ammo is one, in which case the ammo is depleted. When ammo is one the ammo low warning is stopped and the more urgent message that the ammo is depleted is played.
IEnumerator AudioWarning() coroutine below plays the Audio warning and sets _audioWarningOn to true. It then waits for audio to compete and resets _audioWarningOn to false. This prevents a bug where the warning keeps being interrupted when the player fires another laser.
The ammo levels are decreased at the end of the FireWeapons() function, as shown below. The laser shot sound itself uses _playerAudio.PlayOneShot, which allows it be played to completion without being interrupted by audio warnings due to the ammo state. PlayOneShot is not used for the ammo warning to allow warnings to be halted for higher priority messages.
The _uiManager variable , previously assigned and null checked in void Start(), is used to access the UpdateAmmo function to change the private Text _ammoText variable, shown below.