Unity 3D – JS Script – Screen Fader

1. MAIN TOP MENU> GameObject> Create Other> GUI TEXTURE> Inspector, rename it ‘ScreenFader’
2. Inspector> Transform> Position X=0 Y=0 Z=0 (così viene posizionata in basso a sinistra dello schermo)
3. Pixel Inset, X=0 Y=0 W=0 H=0 (non vogliamo che ci siano dei rientri)
4. Inspector> GUI Texture> DRAG E DROP a black bitmap Texture
5. Assign to ‘ScreenFader’ GameObject this JS Script:

SceneFadeInOut.js

#pragma strict

public var fadeSpeed : float = 1.5f;            // Speed that the screen fades to and from black.
private var sceneStarting : boolean = true;     // Whether or not the scene is still fading in.

function Awake ()
{
    // Set the texture so that it is the size of the screen and covers it.
    // Per prima cosa ricopro tutto lo schermo creando un rettangolo di dimensione dello schermo
    guiTexture.pixelInset = new Rect(0f, 0f, Screen.width, Screen.height);
}


function Update ()
{
    // If the scene is starting...
    // Controlla il valore booleano -sceneStarting- se è vero esegue le istruzioni all'interno di -if-
    if(sceneStarting)
        // ... call the StartScene function.
        // richiama la funzione
        StartScene();
}


function FadeToClear ()
{
    // Lerp (interpolate 2 values) the colour of the texture between itself and transparent.
    // Esegue un fading - colore della texture -> completamente trasparente -
    guiTexture.color = Color.Lerp(guiTexture.color, Color.clear, fadeSpeed * Time.deltaTime);
}


function FadeToBlack ()
{
    // Lerp (interpolate 2 values) the colour of the texture between itself and black.
    guiTexture.color = Color.Lerp(guiTexture.color, Color.black, fadeSpeed * Time.deltaTime);
}


function StartScene ()
{
    // Fade the texture to clear.
    FadeToClear();
    
    // If the texture is almost clear...
    // Se il colore è quasi completamente trasparente
    if(guiTexture.color.a <= 0.05f)
    {
        // ... set the colour to clear and disable the GUITexture.
        // Rendi il colore completamente trasparente e disabilita la GUI Texture
        guiTexture.color = Color.clear;
        guiTexture.enabled = false;
        
        // The scene is no longer starting.
        // Imposta la variabile booleana a falso per interrompere il ciclo
        sceneStarting = false;
    }
}


public function EndScene ()
{
    // Make sure the texture is enabled.
    guiTexture.enabled = true;
    
    // Start fading towards black.
    FadeToBlack();
    
    // If the screen is almost black...
    if(guiTexture.color.a >= 0.95f)
        // ... reload the level.
        Application.LoadLevel(0);
}

Inspector> SceneFadeInOut.js> ‘Fade Speed’ variable, assign 0.5 (valore basso -> tempo di fading alto)

NOTICE:

Application.LoadLevel(0);

Setup the correct level number, you can find it inside MAIN TOP MENu> File> Build Settings…
If you have only one scene in your project, just reload it -> .LoadLevel(0)