Sound and music in Unity

Posted on

in

,

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];

Leave a Reply

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

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930