Unity3D - crossfade the basics of working with sound


 1. Create a project.
 2. In the project created two scenes are preserved. For convenience, we can simply call them - 0 1
 3. Pull scene to the window Build Settings (Ctrl + Shift + B).
 4. Drag to the window Project two music files - for the first and second scene.
It is desirable to use * wav - if necessary, it is always possible to squeeze into options inspector UnityÃÂà or * ogg.
 5. Set up our music files: remove a tick checkbox 3D Sound - in our case the volume of the soundtrack / ambient music does not depend on the position of the player with the space relative to the sound source.
Drag one of the audio files in the first stage and the other in the second.
The camera (or character) should be Audio Listener


Smooth attenuation of ambient previous level in the transition to the next level.
Subsequent removal after a certain amount of time.

Create your js script with a, like silly name - call it FadeOut AndDestrTimerWhenNextLvl Load
The first thing we need - the object to "sound" is not destroyed during the transition to the next level.
Why? Then, to make it smooth fading and then remove.

Read the documentation.

Yeah, we need this line:

DontDestroyOnLoad (transform.gameObject);

Based on our requirements, ponder three modifiable variables:

the duration of the sound attenuation
from time to time of loading level to remove the object "sound"
the number of levels on which the script will run -
This is necesarry thing, because the script is universal - we will apply it at different levels.

var fadeTime = 0;
    var levelToExecute = 0;
    var DestroyTime = 0;

So following the script will consist of two functions - "Timer delete" and "damping mechanism."

Let's start with the "Timer delete".
It's all simple:

function OnLevelWasLoaded (level : int) {
        if (level == (levelToExecute))
            Destroy (gameObject, DestroyTime);
            //Destroy (gameObject, 20); 

If the number of the loaded level will correspond to the indicated in the box "levelToExecute", run "Timer delete" - from the time of loading of the level before the time specified by us in the box DestroyTime.
Hmm, why don't we add immediately and run (not yet written) function "damping mechanism" is here?

function OnLevelWasLoaded (level : int) {
        if (level == (levelToExecute))
            FadeAudio(fadeTime, Fade.Out); 
            //the duration of the decay, type the fade - attenuation (not gain)
            Destroy (gameObject, DestroyTime);

Now it is necessary to write a function "damping mechanism".

function FadeAudio (timer : float, fadeType : Fade) {
        var start = fadeType == Fade.In? 0.0 : 1.0; //at the start (of this new level) there will be sound amplification from 0 to 1
        var end = fadeType == Fade.In? 1.0 : 0.0;   //fading occurs at the end of 1 to 0
        var i = 0.0;                                //variable value (volume)
        var step = 1.0/timer;                       //step (a "soft" changes in volume) is equal to one volume / timer
        while (i <= 1.0) {                          //up until the "0" (the volume) is equal to or less than "1" execute,
                                                    //up to obtain the value "0"
            i += step * Time.deltaTime;
            audio.volume = Mathf.Lerp(start, end, i); 
// Mathf.Lerp - find intermediate values according to the available volume of start, end, and the value of "i"
//stretch in time change of sound

Here's what we got:

Smooth increased ambient at boot level

We already know most of what you need for this part.
Add a little bit.

Create a new js script, I'll call him StartFadeIn_CloneTimer_FadeOut_DestrTimer
Please note - the name is not just stupid, it contains the sequence of execution functions.

1. Fade early tack, "unregulated" volume gain occurs from 0 to 1.It should operate as at the start of the level, and at the clone (see below).

2. Fade end track - is damped volume from 1 to 0,activated 10 seconds (for example) to the final of the track.The "unregulated", but not quite - not directly. More on that below.

3. Destruction of the object "track" - adjustable figureThe default is the length of the track in seconds, but not necessarily.We are free to destroy the track at any time, without waiting for the end.The script will automatically start fade decay for 10 seconds before destruction,accordingly this figure.

4. Adjustable fade duration.
According to the written above is 10c
but we'll leave the possibility to change it if necessary.

5. Create a clone of the track - adjustable figure
it is equal to the length of the track, in seconds, 10 seconds less attenuation.

6. As at different levels of the different tracks, do universal script -
add the ability to select the desired object we "sound".

List that we have here the attenuation and amplification, and create four variables:

enum Fade {In, Out}             // to declare the transfer - our "gain" and "attenuation"

    var  prefab :     Transform;    //selection of an object "sound"
    var  DestroyTime: float = 1;    //time (delay) to remove
    var  CloneTime:   float = 1;    //time (delay) before cloning
    var  fadeTime:    float = 1;    //the duration of the extinction / gain

Add the function "Start":

function Start(){
    //launch of the "Spawn" (cloning)
    FadeAudio(fadeTime, Fade.In ); 
    //launch of the "Fade," including the specified variable duration and type of fade - strengthening
    Destroy ((prefab as Transform).gameObject, DestroyTime); 
    //Deletes the selected object sound at the expiration of the time specified in DestroyTime

Now, in order to add the above function. Cloning:

function Spawn(){
    while( true ){
        yield WaitForSeconds(CloneTime); //delay before execution contains a variable CloneTime
    	   for (var i : int = 0;i < 1; i++) 
           { Instantiate (prefab, Vector3(i * 2.0, 0, 0), Quaternion.identity); } //Cloning of the selected object "sound" 
           FadeAudio(fadeTime, Fade.Out); //the duration of the attenuation, fires at the end

The "Fade" we already have - copy-paste it from the first part of the article:

function FadeAudio (timer : float, fadeType : Fade) {
        var start = fadeType == Fade.In? 0.0 : 1.0;
        var end = fadeType == Fade.In? 1.0 : 0.0;
        var i = 0.0;
        var step = 1.0/timer;
        while (i <= 1.0) {
            i += step * Time.deltaTime;
            audio.volume = Mathf.Lerp(start, end, i);

        Debug.Log (audio.volume); 
        //check operation of the fade is logged to the console - you can remove / disable

Here's what we got:

Look length of this track, convert it in seconds = stroyTime
If too lazy to count - you can use an online converter minutes + add the rest of seconds.

Deduct fade duration = Clone Time
Fit the values obtained in the windows.
In perfab add the desired track.

You must see to it that the delay before cloning / fade duration / time of removal does not conflict with the time parameter of the script from the first part of the article -otherwise the transition to the next level track may not be able to be destroyed and begin to create multiple copies of itself.


All data posted on the site represents accessible information that can be browsed and downloaded for free from the web.





User replies

No replies yet