AudioSource.Play() and other simple methods to play sound in Unity3D

Alberto Garcia
2 min readJan 22, 2023

In the case of a 2D Space Shooter, the hierarchy requires an Audio Listener, usually a game component of the Main Camera. This listener picks up all of the sounds being triggered in game. Every game object that emits a sound does so through an Audio Source component; the audio source component has a lot of properties and public methods that may be used to play and alter the sound being played in different cases. For example, the same audio clip is used for the laser shooting, the difference comes that when the triple-shot power-up is enabled, the pitch is higher and the volume is set at the maximum level; the normal shooting instead has a volume of 0.7f and the pitch is slightly lower, to give a single laser texture to sound.

 [SerializeField]
private AudioClip _laserSound;
[SerializeField]
private AudioClip _explosionClip;

private AudioSource _audioSource;


public void ActivateTripleShot()
{
_audioSource.pitch = 1.2f;
_audioSource.volume = 1f;
StartCoroutine(TripleShotActive());
}

IEnumerator TripleShotActive()
{
_tripleShotEnabled = true;
yield return new WaitForSeconds(5.0f);
_audioSource.pitch = 0.9f;
_audioSource.volume = 0.7f;
_tripleShotEnabled = false;
}

The explosion clip is the same for the asteroid, the enemies and the player, but having a lower pitch and a higher volume gives noticeable feedback to the player that the last explosion heard has a different meaning than the usual ones occurring constantly during the game.

 public void Damage()
{
if (_currentHealth < 1)
{
_spawnManager.OnPlayerDeath();
_uiManager.GameOver();
Instantiate(_explosionFire, transform.position, Quaternion.identity);
_audioSource.clip = _explosionClip;
_audioSource.pitch = 0.8f;
_audioSource.volume = 1f;
_audioSource.Play();
Destroy(this.gameObject);
}
}

there are many more properties that may be edited with code to achieve more audio effects through out game design; this simple example shows just how a minor tweak can have a lot of significance for a reusable clip.

This graphical reference to sound waves on volume and pitch portray the difference of how various properties make sound travel; diagram from Measuring Sound article.

Sound traveling

AudioSource.PlayClipAtPoint() is another handy method to optimize sound tasks; it creates an ephemeral Audio Source to play an Audio Clip at a given position in world space. In this case, the clip is played at the pick up position (OnTriggerEnter2D collision).

 [SerializeField]
private AudioClip _powerUpClip;

//Inside the OnTriggerEnter2D() method, call the following line of code:
AudioSource.PlayClipAtPoint(_powerUpClip, transform.position);

Unity’s capabilities to mix sound serve as a very powerful tool in designing immersion. Great enough to create virtual mixing studios.

--

--