Asbjoern Andersen


The talented Maris Tammik is back with the much-awaited 2nd part of his introduction to Game Audio Scripting in Unity. In this installment, they take it to the next level – with insights, tips and plenty of code examples:


Written by Maris Tammik



 

Hey hey! This part two of my intro to scripting for sound people. If you have not read it yet, head here for part one. All the code can be found as a fully functioning Unity project (version 5.5+) on Github. The Github repo reflects the latest state of the project, so if we are referencing parts of code which have changes simply checkout a previous version of the project (a simple guide to git). For the complete code and bug fixes please check the github repository. The code snippets in this article are meant as reference.

In this article we’ll look at:
• Instantiating GameObjects (based on prefabs);
• Creating an audio data format based on ScriptableObjects (instead of prefabs);
• Handling volume in dB and pitch in semitones;
• Adding sound, volume and pitch randomisation;

[tweet_box]An Introduction to Game Audio Scripting (Part 2)[/tweet_box]

Tutorial Ahoy!

To get started, let’s set up a little script that references a sound prefab and instantiates it when needed. In a game environment this could be a script that controls the behavior of an object which needs sound for a specific action. In our case, since we don’t have a game to hook into, let’s simply create a GameObject that spawns a sound on Start. In a game this could be used to trigger an ambience loop. Alternatively, it could be attached to a prefab of a prop for the game that needs a spawning sound.

To get started, we’ll create a new C# script called AudioOnStart which will simply play a sound on the start method. Create a public field for a GameObject where we’ll store the prefab for our sound to be played. Well use the Instantiate method; a generic method which takes a Type to be instantiated as well as the prefab to be copied (more info on generic methods at MSDN).

 

public GameObject SoundPrefab;

void Start ()
{
if (SoundPrefab != null)
{
Instantiate<GameObject>(SoundPrefab, this.transform);
}
}

 

The AudioSourceController we created last time automatically starts the sound in the Start method. Now that we have a script to do just that, let’s hand over the responsibility of starting playback to the AudioOnStart script and remove the Start() method from the AudioSourceController.

The Instantiate method returns a reference to a newly created GameObject. We can store that reference in a local GameObject variable in the Start method so that we may use it. Next we need a reference to the controller. We’ll use the GetComponent method to find the controller script and then call its Play method to make our sound play again. Get component is yet another generic method. This time we’ll specify the AudioSourceController class.

 

void Start()
{
if (SoundPrefab != null)
{
GameObject go = Instantiate<GameObject>(SoundPrefab, this.transform);
AudioSourceController soundInstance = go.GetComponent<AudioSourceController>();
soundInstance.Play();
}
}

 

Alternatively, we could also skip storing the GameObject and AudioSourceController in local variables and call all methods on the result of the previous one, but it looks a bit messy, and easily readable code is far more maintainable.

 

Instantiate<GameObject>(SoundPrefab, this.transform).GetComponent<AudioSourceController>().Play();

 

Pooling & Scriptable Objects

This way of instantiating objects works fine, but is rather limited. Having to create GameObjects for each sound is a rather costly operation in Unity, and creating new sounds involves creating an empty GameObject, attaching a script to it, then dragging it into a folder in the Project tab. Let’s take a look at another approach.

Instead of instantiating GameObjects we can store our sound behaviour in a ScriptableObject (Unity Documentation on this). This is a nice way to package up our audio behaviour but since the ScriptableObject is file on disk and not a component in the game world we are not able to attach neither the AudioSource nor the AudioSourceController we need to play the sound back. So instead we’ll use a technique called pooling to create a repository of empty AudioSourceControllers and take them out of the pool whenever we want to play a sound. The script we’ll create to handle this for us will be the AudioPoolManager. Once a sound is done playing, it goes back into the pool until it’s needed again. The audio data will only be responsible for storing behaviour playback volume and pitch or if the sound is supposed to loop.

To start off, the AudioPoolManager needs a way of keeping track of multiple AudioSourceController scripts. We’ll use a List, which is a data structure accessible by using the System.Collections.Generic namespace at the very top of the script.

Next, we’ll need a way to get controller scripts out of the pool. This GetController method will check the list of available controllers, and if any are found it will remove one from the list and return it. If the list is empty, it must create a new GameObject, add an AudioSourceController component, and then return the newly created controller.

 

public class AudioPoolManager
{
private List<AudioSourceController> _pool = new List<AudioSourceController>();

public AudioSourceController GetController()
{
AudioSourceController output = null;
if (_pool.Count > 0)
{
output = _pool[0];
_pool.Remove(output);
return output;
}
else
{
GameObject go = new GameObject("AudioController");
output = go.AddComponent<AudioSourceController>();
return output;
}
}
}

 

To get access to the pool from any script without a direct reference, we can implement a simple Singleton pattern. This will make sure that there will only be one single AudioPoolManager at any time.

To do this we can use a private static field and a public property of type AudioPoolManager where the Getter will check if there is an instance of the pool manager already. If the static instance is null it will create one, otherwise it will simply return the instance. Preferably we put this at the very head of a class definition so it’s immediately clear we are dealing with a Singleton class when opening up the script in the editor..

 

private static AudioPoolManager _instance;
public static AudioPoolManager Instance
{
get
{
if(_instance == null)
{
Debug.LogWarning(“Instanciating AudioPoolManager.”);
_instance = new AudioPoolManager();
}
return _instance;
}
}
 

We’ll use the “static” keyword so that we can access the pool without storing a reference to it. It also makes sure that the field is the same in every instance of the script. If we only access the pool manager via the Instance property, it will only ever create one instance and return that every time we need access to the pool. There is a slight overhead to this, so if we need access to the pool over and over from the same script, it makes sense to cache the pool instance in a private variable (see below). Check out other design patterns here.

Now that we have the pool manager set up, we need to setup our data format. Let’s create a new class called AudioData which inherits from ScriptableObject instead of the MonoBehaviour default. For now we can move the properties which were stored in the AudioSourceController script. Deleting these properties in the controller script this will break our previously setup prefabs, so beware! After removing those properties we will also have to remove the SetProperties call in the controllers Play method.

Then, we will have to add an attribute above the class definition so that we can create AudioData objects in our project. This will enable us to use the Assets/Create/AudioData menu option as well as the right-click create option in the project tab. Now, all we need is a way to play the sound back. To get this going, we can simply add a public Play method to the AudioData itself which will get an AudioSourceController from the pool, set its properties, and call the Play method before returning the controller.

 

using UnityEngine;

[CreateAssetMenu()] public class AudioData : ScriptableObject
{
public AudioClip Clip;
[Range(0, 1)] public float Volume = 1f;
[Range(.25f, 3)] public float Pitch = 1f;
public bool Loop = false;
[Range(0f, 1f)] public float SpacialBlend = 1f;

public AudioSourceController Play()
{
AudioSourceController controller = AudioPoolManager.Instance.GetController();
controller.SetSourceProperties(Clip, Volume, Pitch, Loop, SpacialBlend);
controller.Play();
return controller;
}
}

 

We can adjust The aAudioOnStart class to hold an AudioData reference instead of a GameObject, and the Start method will become a whole lot simpler as a result:

 

using UnityEngine;

public class AudioOnStart : MonoBehaviour
{
public AudioData Sound;

void Start()
{
if (Sound != null)
{
Sound.Play();
}
}
}

 

What’s missing now is a way to get sounds back into the pool. First we need a public PutController method on the AudioPoolManager to store the controller in the pools list. This method will make sure the list does not already contain that specific controller, and then add it to the list.

 

public void PutController(AudioSourceController controller)
{
if (_pool.Contains(controller) == false)
_pool.Add(controller);
}
 

Next, we will implement a public Stop method on the controller script which stops the AudioSource from playing back and then puts the controller back into the pool:

 

public void Stop()
{
_source.Stop();
AudioPoolManager.Instance.PutController(this);
}
 

As we are dealing with games and they mostly happen to have objects moving on the screen it’s time to implement spatial settings. First, we need a way for the controller script to access its position which is being determined by the Transform component present in each GameObject. We can get the GameObject’s Transform in the Awake method of the controller and cache it in a private variable. This is a good idea since calls to the Unity API often have a little processing overhead for all sorts of error handling and safety.

If we have sounds following GameObjects we’ll want to update the position every frame. When we start playing many sounds at once, the savings we’ll achieve by having this call once per controller will add up quickly.

 

private Transform _transform;

public void SetPosition(Vector3 position)
{
_transform.position = position;
}

 

Now it probably makes sense to pass the position before we initially play the sound, so we’ll pass a Vector3 parameter to the Play method of the AudioData and set the position right before the Play method call of the controller.

 

public AudioSourceController Play(Vector3 position)
{
AudioSourceController controller = AudioPoolManager.Instance.GetController();
controller.SetSourceProperties(Clip, Volume, Pitch, Loop, SpacialBlend);
controller.SetPosition(position);
controller.Play();
return controller;
}
 

We could also add an Overload to the Play method to pass in a Transform instead:

 

public AudioSourceController Play(Transform parent)
{
AudioSourceController controller = Play(parent.position);
controller.SetParent(parent);
return controller;
}
 

We are calling a SetParent method on the AudioSourceController.

 

public void SetParent(Transform parent)
{
_transform = parent;
}
 

The reason we handle the Transform separately and don’t just set the position and be done with it is that we can now check whether the Transform has moved and update the sound’s position in space accordingly. For this purpose we can use MonoBehaviours LateUpdate method which gets called at the end of every frame. This is so the sound updates its position after the entire game simulation happened and all the other GameObjects have been moved and rendered at their new locations.

This update method is also a great place to check if the sound is still playing. If not, and if it’s not in the pool, we want to call the Stop method. For this purpose we also declare a private boolean variable which is set to true when the Play method is called.

 

void LateUpdate()
{
if (_claimed && _source.isPlaying == false)
{
Stop();
}
if(_parentObject != null)
{
_transform.position = _parentObject.position;
}
}
 

At this point it makes sense to implement a Reset method to call every time the controller script stops. This will handle setting the parent Transform to null and resetting the claiming state.

 

private void Reset()
{
_parentObject = null;
_claimed = false;
}
 

Updating the position of the sound means a call to the Unity API every frame. We should actually first check if the new position is any different from the old one, but checking the position is itself call to the Unity framework. Instead we will cache the current position in a private Vector3 field and update the sound’s Transform and cached position only if it has changed.


Popular on A Sound Effect right now - article continues below:


Trending right now:

  • ⏰ For a very limited time:
    Add this library to the cart and enter ah4launch in the cart coupon field – to sprinkle an extra launch discount, on top of the current discount!

    Animal Hyperrealism Vol IV is a sound library containing animal vocalisations, from real to designed creatures totaling more than 2000 individual sounds in 294 files. The sounds were recorded in zoos, and wildlife centers.

    The asset list includes but is not limited to: hippos, hyenas, vultures, dwarf mongooses, elephants, African cranes, parrots, tigers, pigmy hippos, rhea ostriches, brown bears, pheasants, wildebeests, African wild dogs and many more. The content has been recorded at 192KHz with a Sanken CO100K, an Avisoft CMPA and a Sennheiser 8050 for center plus two Sennheiser MKH8040 for stereo image.

    The resulting ultrasonic spectrum is rich and allows for truly extreme manipulation of the content.

    15 %
    OFF
  • FOUR ELEMENTS - Rock The Speakerbox Professional SFX

    Master the Art of Bending the Elemental Forces

     

    Unleash the raw power of fire, water, earth, and air with this comprehensive 9 GB sound library featuring 3050 high-quality sound effects across 630 files. Whether you’re designing cinematic soundscapes or enhancing video games Four Elements delivers the tools you need to harness the energy of the natural world.

    Construction Kit – 2443 Sounds

    A treasure trove of raw, organic, and processed sounds including seamless loops divided into Fire, Water, Air, Earth and Explosion categories. Customize every detail with an extensive selection of sound components.

    • Organic Fire: Campfire sizzles, torch whooshes, and flame bursts.
    • Processed Fire: Distorted impacts and unique crackles.
    • Organic Earth: Rock crashes, gravel scrapes, and heavy stone hits.
    • Processed Earth: Stylized rumbles and granular textures.
    • Organic Water: Ocean waves, hydrophone bubbles, and fluid splashes.
    • Processed Water: Underwater whooshes and stylized liquid smashes.
    • Organic Air: Bamboo swishes, cloth movements, and pressure bursts.
    • Processed Air: Filtered gusts and dynamic noise sweeps.
    • Explosion: Firework detonations, Butane bursts, and cinematic impacts.

    Building Blocks – 416 Sounds

    Game-ready sound layers featuring Impacts, Whooshes, and Textures as seamless loops. Elevate transitions and enhance atmospheres with loops and pre-designed sound layers.

    • Fire: Explosive bursts, blazing infernos, and warm embers.
    • Earth: Ground-shaking impacts, crumbling terrain, and heavy collisions.
    • Water: Cascading waves, serene rivers, and underwater ambiences.
    • Air: Whispering breezes, stormy turbulence, and slicing gusts.

    Design Kit – 192 Sounds

    A collection of ready-to-use sound effects divided into Attack, Bend, and Explosion categories for quick integration into your projects. Perfect for high-energy scenes and immersive storytelling.

    • Fire: Crackling flames, fiery bursts, and roaring infernos.
    • Earth: Crushing impacts, shifting ground, and massive land eruptions.
    • Water: Splashes, fluid manipulations, and crashing tidal waves.
    • Air: Slicing winds, swirling currents, and thunderous gusts.

     

    Four Elements gives you complete creative control, blending organic recordings with processed sound layers to meet the demands of any project. Master the forces of nature with Four Elements. Let your creativity ignite.

     

    Keywords:

    Elements, Fire, Water, Earth, Air, Wave, Water, Liquid, Rock, Cast, Stone, Pebble, Torch, Gas, Flame, Campfire, Sizzle, Burst, Scrape, Whoosh, Impact, Texture, Attack, Bend, Bending, Explosion, Processed, Surge, Quake, Hit, Flow, Burn, Ignite, Drop, Smack, Destruction, Rumble, Hiss, Blow, Wind, Cloth, Movement, Underwater, Bubble, Ocean, River, Lake, Firework, Firecracker, Bang, Blast, Detonation, Magic, Fantasy, Forces, Fire Magic, Water Magic, Earth Magic, Fire Air, Fire Effect, Fire Whoosh, Water Whoosh, Seamless Loop, Loop, Fire Cast, Water Cast, Earth Cast, Air Cast

  • Weather Sound Effects Florida Thunder Play Track 500+ sounds included, 300 mins total $49

    Florida Thunder by Eric Berzins contains 111 distinct wav files with over 200 dry thunderclaps and over 300 thunderclaps with rain. All files were recorded in the US state of Florida between 2021 and 2025. Florida has more lightning strikes than any other U.S. state! All files have been meticulously edited and cleaned, and have embedded UCS-compliant Soundminer metadata.

    17 %
    OFF
    Ends 1759269599
  • Electricity Sound Effects Thunder Claps Play Track 40 sounds included, 15 mins total $80

    Captured over five years in a secluded forest house — THUNDER CLAPS delivers the raw, untamed power of nature.

    Recording lightning strikes at close range is one of the most difficult — and dangerous — things in field recording. Capturing them in a secluded home in the heart of the countryside has made this process a bit easier.

    Now sit and feel the intensity of authentic close, medium, and distant thunder strikes, booms, and rumbles — recorded at up to 32-bit / 192kHz resolution for unmatched detail and dynamic range.

    There are no other sounds in these files but the booming of the strikes. All tracks feature clean, isolated thunder clapsNO rain, NO wind, NO background noise — so you won’t waste time cleaning or editing. Just drag, drop, and unleash the storm.

    Note: The SoundCloud demo includes a rain texture just for protection purposes. This is not included in the library.


Latest releases:

  • Door Sound Effects Extra Door Stops Play Track 140 sounds included, 3 mins total $9.99

    EXTRA DOOR STOPS – is an auxiliary sound library containing 140 unique sound effect files of door stops. From metallic flubs and taps to bass winding and vibrating springs. Whether it’s funny relief or motor-like springs you’re looking for; This Extra sound effects library will help supplement the domestic door stopping needs, of your next project. Extra Door Stops comes in at over 3 minutes and was recorded at 192kHz / 32bit using an ultrasonic microphone. All of our libraries comply with the Universal Category System naming convention standard, allowing for accurate and easy granular searches.

    50 %
    OFF
  • ⏰ For a very limited time:
    Add this library to the cart and enter ah4launch in the cart coupon field – to sprinkle an extra launch discount, on top of the current discount!

    Animal Hyperrealism Vol IV is a sound library containing animal vocalisations, from real to designed creatures totaling more than 2000 individual sounds in 294 files. The sounds were recorded in zoos, and wildlife centers.

    The asset list includes but is not limited to: hippos, hyenas, vultures, dwarf mongooses, elephants, African cranes, parrots, tigers, pigmy hippos, rhea ostriches, brown bears, pheasants, wildebeests, African wild dogs and many more. The content has been recorded at 192KHz with a Sanken CO100K, an Avisoft CMPA and a Sennheiser 8050 for center plus two Sennheiser MKH8040 for stereo image.

    The resulting ultrasonic spectrum is rich and allows for truly extreme manipulation of the content.

    15 %
    OFF
  • Weather Sound Effects Hyper Thunder Play Track 800+ sounds included $49.50

    Hyper Thunder is a colossal collection of thunder and lightning, 100% crafted from the ground up using innovative synthesized technics and props recordings. Not a single real life thunder recording was used. using synthesis and props manipulation crafted to deliver impact far beyond natural recordings. Built entirely from innovative synthesis and props recordings, this library pushes the boundaries of weather sound design—perfect for when you need the raw energy of a storm dialed up to cinematic extremes.

    Featuring over 800 files, Hyper Thunder spans everything from subtle distant rumbles and rolling thunder to razor-sharp lightning strikes and earth-shaking impacts. With both designed hits and source layers, you have full control—drop in ready-to-use power or sculpt your own stormscapes using the source recordings.

    Created in collaboration with Bruits.Studio’s Vincent Fliniaux and Tibo Csuko—longtime SoundMorph contributors to acclaimed libraries like Robotic Lifeforms 2 and WATER— Hyper Thunder blends technical mastery with bold creativity.

    Key Features

    • 800+ files of synthesized thunder and lightning
    • Both designed hits and source layers for full creative control
    • Covers subtle distant rumbles through to massive cinematic impacts
    • Crafted 100% from synthesis for a unique, larger-than-life sound
    • Perfect for film, games, trailers, and any project needing storm power
    • Created in collaboration with Bruits.Studio’s Vincent Fliniaux and Tibo Csuko (Robotic Lifeforms 2, WATER)

    From atmospheric detail to explosive drama, Hyper Thunder gives you thunder and lightning that are bigger, subtler, and more versatile than nature itself.

    50 %
    OFF
  • 638 meticulously processed stereo fire spells sound effects recorded in 96 khz and 24 bits for high audio definition.

    The collection comes with hundreds of variations, more than 1 hour of content and many different type of fire spells. It also includes source sounds for more flexibility for your projects.

    This collection is perfect for any films, video games or trailers.

    The library is fully focused on fire spells. You will find simple one shot magic firebolt, powerful high level fire spells, fire sword, berserker enchantments and so on. Spells such as fireball,  firewall, rain of fire, meteor, fire nova, magma storm, pyroblast, sword of Avernus, etc. are included in this library.

     

    THE ARCANE FIRE SPELLS
    38 %
    OFF
  • Immerse yourself in an atmosphere of natural power and tranquility with the “Rain and Thunderstorm” sound collection, consisting of 4 Vol-s.
    This collection features a variety of looped sounds: light rain, night rain with loud thunderclaps, and other effects that will help you create the perfect atmosphere – from a quiet, secluded night, long scenes, or endless atmospheric effects without abrupt transitions, to a dramatic thunderstorm on the horizon.
    The recording was made by a Zoom H3-VR recorder in the Ambisonics A format (96 kHz 24 Bit) and then converted to the AmbiX and Stereo formats (96 kHz 24 Bit), which are located in different folders of this sound pack.

Need specific sound effects? Try a search below:


Utility Functions

Before we randomize volume and pitch of our sounds, let’s look at Unity’s documentation of the AudioSource. The volume in Unity is described as a floating point value between 0 and 1. This can be understood in terms of an amplitude factor. Multiply the amplitude by 1 and we playback a sound at unity gain. If the volume is 0.5, the amplitude is halved which results in a volume reduction of 6dB. To decrease the volume by another 6dB simply set the volume to 0.25 and so on. The volume in Unity’s AudioSource property behaves in a linear fashion as opposed to logarithmically; the way sound designers are used to interacting with volume. Another side effect is that if we randomize the volume factor by an amount of 0.1, this random factor means very little if our volume sits at around 1, but can have a huge impact when the initial value is lower. To solve this, we’ll create a helper function to randomize the volume by a certain Decibel amount instead.

A quick web-search spits out plentiful results for converting gain factors to decibels. The conversion algorithm i based on this one here, which results in the following code:

 

using UnityEngine;

public class AudioUtils
{
public static float DecibelToLinear(float dB)
{
if (dB > -80)
return Mathf.Clamp01(Mathf.Pow(10.0f, dB / 20.0f));
else
return 0;
}
public static float LinearToDecibel(float linear)
{
if (linear > 0)
return Mathf.Clamp(20.0f * Mathf.Log10(linear), -80f, 0f);
else
return -80.0f;
}
}

 

Here is a quick refresher about the Decibel unit.

There is a minimum threshold of -80dB to avoid unnecessary calculation at very low volumes and each conversion is wrapped in a Clamp function to make sure my output is always within a usable range. We are using static function so the Conversion can be called without having to hold a reference to an instance of the Utility class.

The same issue arises with the AudioSource’s pitch property. A pitch of 1 translates to normal playback speed, 0.5 translates to half the playback speed meaning -12 semitones and so on. Unity also supports negative pitch which means the sound will play backwards and if the pitch is set to 0 the sound will start playing but never progress which means it is taking up a voice that will play back that one sound forever. Another source for neat audio bugs ;)

Finding formulas to solve this is a bit harder. I believe I got the initial idea for this in “The Audio Programming Book” (MIT press). These problems often have been solved before. Do some research and borrow exchange ideas with other audio coders. The power of collaboration!

So here is:

 

private static float twelfthRootOfTwo = Mathf.Pow(2, 1.0f / 12);
public static float St2pitch(float st)
{
return Mathf.Clamp(Mathf.Pow(twelfthRootOfTwo, st), 0f, 4f);
}
public static float Pitch2st(float pitch)
{
return Mathf.Log(pitch, twelfthRootOfTwo);
}

 

We’ll stick that into the AudioUtils class as well and move on.

 
Randomisation

Now that we have a way to turn our volume and pitch values into a randomizable format we can add those properties to our audio data. First we need to use the new number format but we can add some random ranges at the same time.

 

public float Volume = 0f;
[Range(-20, 0)] public float RandomVolume = 0f;
[Range(-24, 24)] public float Pitch = 0f;
[Range(0, 12)] public float RandomPitch = 0f;
 

We need to adjust the Play() method as well to translate from the AudioData to the format the AudioSource in Unity expects. To generate Random numbers we’ll use the UnityEngine.Random.Range(float min, float max).

 

float volume = AudioUtils.DecibelToLinear( Random.Range(-80, Volume + RandomVolume) );
float pitch = AudioUtils.St2pitch( Random.Range(-80, Pitch + RandomPitch) );
controller.SetSourceProperties(Clip, volume, pitch, Loop, SpacialBlend);
 

We can simply generate a random number between “0” and the random range by using the Random.Range() method in the AudioData.Play() call like this:

 

float volGen = AudioUtils.DecibelToLinear( Random.Range(Volume + RandomVolume, 0) );
float pitchGen = AudioUtils.St2pitch( Random.Range(Pitch - RandomPitch, Pitch + RandomPitch) );
controller.SetSourceProperties(Clip, volGen, pitchGen, Loop, SpacialBlend);
 

Now when we play the sound it will randomly generate a pitch and a volume and apply those to the AudioSourceController every time a new Play() call comes in.

Randomizing volume and pitch only gets us so far so let’s try to have some variation in samples as well. First we need a way to store multiple sound files in the AudioData. For this we’ll use a list of type AudioClip.

 

List<AudioClip> Sounds = new List<AudioClip>();
 

To be able to declare a variable of type List we need to include the System.Collections.Generic namespace.

 

using System.Collections.Generic;
 

Next we’ll need to get a random clip from the list but first we’ll check if the list is not empty. The index defaults to “0” which will return the first item in the list unless the list is longer than one item in which case a random index is generated. Many data structures start with an index of 0 and count up from there.

 

private AudioClip GetClip()
{
if (Sounds.Count == 0)
{
Debug.LogWarning("AudioData does not contain any AudioClips.");
return null;
}
int index = 0;
if (Sounds.Count > 1)
{
index = Random.Range(0, Sounds.Count - 1);
}
return Sounds[index];
}
 

Now we can get rid of the single Clip field and use GetClip() to update the AudioData.Play() method.

 

controller.SetSourceProperties(GetClip(), volGen, pitchGen, Loop, SpacialBlend);
 

You will notice that the AudioClip we assigned to our AudioData previously has been replaced with a list of sound represented like this:

If we click on the “foldout” arrow we can set the length of the list and drop a different sound into each AudioClip field.

And that’s that! We now have a bunch of randomization options which will increase the mileage of our audio assets and reduce the “fakeness” feeling of our game tricking the brain into buying into our world building efforts a bit more.

Here are a couple of ideas on where one might improve on this system now: It would be nice to keep track of the last played index and make sure it is not repeated or even a list of previously played indexes to check against. The AudioSource still has a lot of interesting properties we are not accessing yet like minimum and maximum distance or distance falloff curve (Unity Documentation on the AudioSource component) which would add a lot of functionality and control to the tool. It’s also worth reading through the manual section on the AudioSource component as there is a lot of valuable information in there. Also the AudioPoolManager should maybe create a minimum size pool on Awake() so the cost of creating new GameObjects does not have to be paid during game play and maybe even limit the amount of objects it can create so there will never be more than – say 64 voices in a scene at any given time. To make sure we can play this many sounds at once we also have to check the Project’s audio manager (Unity Documentation)

Next time we will take a look at doing work over time using Coroutines – first and foremost fading sounds in and out. We’ll also investigate custom inspector to make it easier to use out AudioData class, add drag and drop support and other neat features. Something that might be interesting but may be a bit over scope for the next tutorial would be a RTPC system (real time parameter control) to change a sound’s behaviour as it is playing.

Hopefully you found this article interesting and you will experiment and play around by adding more properties and functionality to the AudioData class.

love

Maris
 

A big thanks to Maris Tammik for this second game audio scripting tutorial!
In case you missed it, here’s the 1st installment. And do keep an eye out for more – coming soon.


 

ABOUT MARIS TAMMIK

Maris Tammik is an audio programmer at A Shell In The Pit Audio, where they build implementation tools for sound designers. Their passion lies with that magical moment where sound meets code. You can follow Maris on twitter @chtammik or find them at tammik.ca.

 

Please share this:


 



 
 
THE WORLD’S EASIEST WAY TO GET INDEPENDENT SOUND EFFECTS:
 
A Sound Effect gives you easy access to an absolutely huge sound effects catalog from a myriad of independent sound creators, all covered by one license agreement - a few highlights:

  • ⏰ For a very limited time:
    Add this library to the cart and enter ah4launch in the cart coupon field – to sprinkle an extra launch discount, on top of the current discount!

    Animal Hyperrealism Vol IV is a sound library containing animal vocalisations, from real to designed creatures totaling more than 2000 individual sounds in 294 files. The sounds were recorded in zoos, and wildlife centers.

    The asset list includes but is not limited to: hippos, hyenas, vultures, dwarf mongooses, elephants, African cranes, parrots, tigers, pigmy hippos, rhea ostriches, brown bears, pheasants, wildebeests, African wild dogs and many more. The content has been recorded at 192KHz with a Sanken CO100K, an Avisoft CMPA and a Sennheiser 8050 for center plus two Sennheiser MKH8040 for stereo image.

    The resulting ultrasonic spectrum is rich and allows for truly extreme manipulation of the content.

    15 %
    OFF
  • FOUR ELEMENTS - Rock The Speakerbox Professional SFX

    Master the Art of Bending the Elemental Forces

     

    Unleash the raw power of fire, water, earth, and air with this comprehensive 9 GB sound library featuring 3050 high-quality sound effects across 630 files. Whether you’re designing cinematic soundscapes or enhancing video games Four Elements delivers the tools you need to harness the energy of the natural world.

    Construction Kit – 2443 Sounds

    A treasure trove of raw, organic, and processed sounds including seamless loops divided into Fire, Water, Air, Earth and Explosion categories. Customize every detail with an extensive selection of sound components.

    • Organic Fire: Campfire sizzles, torch whooshes, and flame bursts.
    • Processed Fire: Distorted impacts and unique crackles.
    • Organic Earth: Rock crashes, gravel scrapes, and heavy stone hits.
    • Processed Earth: Stylized rumbles and granular textures.
    • Organic Water: Ocean waves, hydrophone bubbles, and fluid splashes.
    • Processed Water: Underwater whooshes and stylized liquid smashes.
    • Organic Air: Bamboo swishes, cloth movements, and pressure bursts.
    • Processed Air: Filtered gusts and dynamic noise sweeps.
    • Explosion: Firework detonations, Butane bursts, and cinematic impacts.

    Building Blocks – 416 Sounds

    Game-ready sound layers featuring Impacts, Whooshes, and Textures as seamless loops. Elevate transitions and enhance atmospheres with loops and pre-designed sound layers.

    • Fire: Explosive bursts, blazing infernos, and warm embers.
    • Earth: Ground-shaking impacts, crumbling terrain, and heavy collisions.
    • Water: Cascading waves, serene rivers, and underwater ambiences.
    • Air: Whispering breezes, stormy turbulence, and slicing gusts.

    Design Kit – 192 Sounds

    A collection of ready-to-use sound effects divided into Attack, Bend, and Explosion categories for quick integration into your projects. Perfect for high-energy scenes and immersive storytelling.

    • Fire: Crackling flames, fiery bursts, and roaring infernos.
    • Earth: Crushing impacts, shifting ground, and massive land eruptions.
    • Water: Splashes, fluid manipulations, and crashing tidal waves.
    • Air: Slicing winds, swirling currents, and thunderous gusts.

     

    Four Elements gives you complete creative control, blending organic recordings with processed sound layers to meet the demands of any project. Master the forces of nature with Four Elements. Let your creativity ignite.

     

    Keywords:

    Elements, Fire, Water, Earth, Air, Wave, Water, Liquid, Rock, Cast, Stone, Pebble, Torch, Gas, Flame, Campfire, Sizzle, Burst, Scrape, Whoosh, Impact, Texture, Attack, Bend, Bending, Explosion, Processed, Surge, Quake, Hit, Flow, Burn, Ignite, Drop, Smack, Destruction, Rumble, Hiss, Blow, Wind, Cloth, Movement, Underwater, Bubble, Ocean, River, Lake, Firework, Firecracker, Bang, Blast, Detonation, Magic, Fantasy, Forces, Fire Magic, Water Magic, Earth Magic, Fire Air, Fire Effect, Fire Whoosh, Water Whoosh, Seamless Loop, Loop, Fire Cast, Water Cast, Earth Cast, Air Cast

  • Capture the moment with Analog and Digital Cameras Ultimate Bundle! Find the true sound of it with Vadi Sound Library.

    About Analog and Digital Cameras Ultimate SFX Bundle

    Analog and Digital Cameras Ultimate Bundle gives you access to 1.000+ communication, digital, mechanical and equipment sound effects that you need for your related projects and room for further sound design with the flexible texture of the sounds for customization.

    This is a unique bundle that has sounds of Minolta XG9, Lubitel 2, Horizon 202, Mamiya 645J, and many more camera sounds in 500 sound files in 24bit/192 KHz Wav format with easy to navigate naming. It is a thoroughly researched collection of very high-resolution sound effects, recorded over a 4 month period, in collaboration with professional photographers specialized in both vintage and modern cameras.

    36 wonderful cameras and accessories were meticulously recorded with a very low noise floor, resulting in 1000+ pristine sounds of camera, shutter and related sound effects. There are recordings of different shutter speeds, shutter release lever, attaching and detaching lenses, battery chamber, flashlights charging and loading sounds, camera click button, diaphragm ring and more! We paid attention to include different speeds and variations of each action.

    36 Cameras and Their Accessories Inside
    Nikon SB900, Godox, Nikon Speedlight, Rhymelight, Sigma 35 mm, Sony A7M3, Canon 6D Mark II, Canon A1, Canon AE1 Program, Canon EOS 5d Mark IV, Diana F+, FisherPrice Toy Camera, Fujifilm Instant Camera, Fujifilm X-Pro 2, Horizon 202, Kodak EK 160-EF, Lubitel 2, Mamiya 645J, Minolta Hi-Matic G, Minolta XD11, Minolta XG9, Nikon F4, Nikon F75, Nikon L35AF, Olympus Stylus, Olympus Zoom Dix, Pentax PC55, Pocket Camera C-T1, Snap Sights Underwater Camera, Sony A6500, Sony A7 M3, Sony DCR HC 96, Vivitar EZ250, Yashica Mini, Zenit 122, Zenit E, Zorki 4K.

    Keywords including Actions, Parts, Equipment and Style
    Shutter, camera, analog, digital, battery, case, zoom, auto focus, ring movement, flash, mechanics, electronics, grabbing, leather, metal, photography, digital, analog, manual, video, flash bulb, latching, speed, button, punch, release, crank, motor, grinding, lens, squeak, handling, lens, click, pop, loading, triggering, assembling, para-soley, compensation, switch, mode, rumbling, sun-shade, Diaphragm Ring, turning, Viewfinder, Display, Lever, timer, picture, bleep, film, winding, rewinding, flashlight, light, attaching, detaching, power on and power off, UV filter, sliding, aperture, take-up spool, shot, loading, inserting, spinning, charging, malfunctioning, hitting, knob, MAS, auto-setting, exposure, selecting, short, long, repetitive, multiple, quiet, subtle, game, film, video, movie, Foley.

    What else you may need
    You may also want to check out our Mechanicals SFX Pack for access to 600+ mechanics, tools, Foley and equipment sound effects.

    52 %
    OFF
Explore the full, unique collection here

Latest sound effects libraries:
 
  • Door Sound Effects Extra Door Stops Play Track 140 sounds included, 3 mins total $9.99

    EXTRA DOOR STOPS – is an auxiliary sound library containing 140 unique sound effect files of door stops. From metallic flubs and taps to bass winding and vibrating springs. Whether it’s funny relief or motor-like springs you’re looking for; This Extra sound effects library will help supplement the domestic door stopping needs, of your next project. Extra Door Stops comes in at over 3 minutes and was recorded at 192kHz / 32bit using an ultrasonic microphone. All of our libraries comply with the Universal Category System naming convention standard, allowing for accurate and easy granular searches.

    50 %
    OFF
  • ⏰ For a very limited time:
    Add this library to the cart and enter ah4launch in the cart coupon field – to sprinkle an extra launch discount, on top of the current discount!

    Animal Hyperrealism Vol IV is a sound library containing animal vocalisations, from real to designed creatures totaling more than 2000 individual sounds in 294 files. The sounds were recorded in zoos, and wildlife centers.

    The asset list includes but is not limited to: hippos, hyenas, vultures, dwarf mongooses, elephants, African cranes, parrots, tigers, pigmy hippos, rhea ostriches, brown bears, pheasants, wildebeests, African wild dogs and many more. The content has been recorded at 192KHz with a Sanken CO100K, an Avisoft CMPA and a Sennheiser 8050 for center plus two Sennheiser MKH8040 for stereo image.

    The resulting ultrasonic spectrum is rich and allows for truly extreme manipulation of the content.

    15 %
    OFF
  • Weather Sound Effects Hyper Thunder Play Track 800+ sounds included $49.50

    Hyper Thunder is a colossal collection of thunder and lightning, 100% crafted from the ground up using innovative synthesized technics and props recordings. Not a single real life thunder recording was used. using synthesis and props manipulation crafted to deliver impact far beyond natural recordings. Built entirely from innovative synthesis and props recordings, this library pushes the boundaries of weather sound design—perfect for when you need the raw energy of a storm dialed up to cinematic extremes.

    Featuring over 800 files, Hyper Thunder spans everything from subtle distant rumbles and rolling thunder to razor-sharp lightning strikes and earth-shaking impacts. With both designed hits and source layers, you have full control—drop in ready-to-use power or sculpt your own stormscapes using the source recordings.

    Created in collaboration with Bruits.Studio’s Vincent Fliniaux and Tibo Csuko—longtime SoundMorph contributors to acclaimed libraries like Robotic Lifeforms 2 and WATER— Hyper Thunder blends technical mastery with bold creativity.

    Key Features

    • 800+ files of synthesized thunder and lightning
    • Both designed hits and source layers for full creative control
    • Covers subtle distant rumbles through to massive cinematic impacts
    • Crafted 100% from synthesis for a unique, larger-than-life sound
    • Perfect for film, games, trailers, and any project needing storm power
    • Created in collaboration with Bruits.Studio’s Vincent Fliniaux and Tibo Csuko (Robotic Lifeforms 2, WATER)

    From atmospheric detail to explosive drama, Hyper Thunder gives you thunder and lightning that are bigger, subtler, and more versatile than nature itself.

    50 %
    OFF
  • 638 meticulously processed stereo fire spells sound effects recorded in 96 khz and 24 bits for high audio definition.

    The collection comes with hundreds of variations, more than 1 hour of content and many different type of fire spells. It also includes source sounds for more flexibility for your projects.

    This collection is perfect for any films, video games or trailers.

    The library is fully focused on fire spells. You will find simple one shot magic firebolt, powerful high level fire spells, fire sword, berserker enchantments and so on. Spells such as fireball,  firewall, rain of fire, meteor, fire nova, magma storm, pyroblast, sword of Avernus, etc. are included in this library.

     

    THE ARCANE FIRE SPELLS
    38 %
    OFF
  • Immerse yourself in an atmosphere of natural power and tranquility with the “Rain and Thunderstorm” sound collection, consisting of 4 Vol-s.
    This collection features a variety of looped sounds: light rain, night rain with loud thunderclaps, and other effects that will help you create the perfect atmosphere – from a quiet, secluded night, long scenes, or endless atmospheric effects without abrupt transitions, to a dramatic thunderstorm on the horizon.
    The recording was made by a Zoom H3-VR recorder in the Ambisonics A format (96 kHz 24 Bit) and then converted to the AmbiX and Stereo formats (96 kHz 24 Bit), which are located in different folders of this sound pack.


   

3 thoughts on “An Introduction to Game Audio Scripting in Unity (Part 2)

  1. Amazing tutorial!

    Thanks a lot Chris! It opens my mind to a new way of using audio in Unity.

    Hope some more coming.

  2. Thanks for this article but I got lost in the middle part. Is there a link to a working sample project where we can actually test this?

Leave a Reply

Your email address will not be published. Required fields are marked *

HTML tags are not allowed.