< Back to Game Dev, Unity

Sound and music in Unity

To add sound/music add the ‘Audio Source’ component to an object. Put your sound files in the ‘Resources’ folder ideally in it’s own folder called maybe ‘sounds’. You can drag a sound file into the ‘AudioClip’ area and tick ‘Play on Awake’ and ‘loop’ for background music. That’s all you need for basic background music.

To swap the audio file and only play it after something happens (like pressing a button) you would do something like this:

bgMusic = GetComponent<AudioSource> ();
AudioClip newMusic = (AudioClipResources.Load("sounds/fileName");
bgMusic.clip = newMusic;
bgMusic.Play ();

The full folder path in this example is Assets/Resources/sounds. Also note the file extension is not included. The rest is pretty straight forward.

You can also attach multiple Audio Sources and reference them like so:

var aSources = GetComponents<AudioSource>(); 
        var1aSources[0];
        var2aSources[1];
        var3aSources [2];
Be Sociable, Share!

Leave a Reply

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