Screen Fader in Unity

Posted on

in

,

Basically this is big black box to fade in and out over everything else to transition between screens. First I made a UI Image that is the same width as the canvas and then stretched it’s height to fill the rest of the screen like so:

gameObject.transform.localScale = new Vector2 (1,(float)Screen.height/(float)Screen.width);

I add a “Canvas Group” component to the game object to control whether it blocks the buttons behind it (because I don’t want buttons clickable during the animation – only after). I tick the ‘Interactable’ and ‘Block Raycasts’ because all scenes will start will the screen fader active and so I want it to start off blocking. In the Start function I make it run fadeInScreen (); which looks like so:

public void fadeInScreen(){
        blockBtns (true);
        black.CrossFadeAlpha (0fadeTime,true);
        StartCoroutine(blockBtns (false));
    }
IEnumerator blockBtns(bool b00l){
        yield return StartCoroutine(CoroutineUtil.WaitForRealSeconds(fadeTime));
        canGroup = gameObject.GetComponent<CanvasGroup> ();
        canGroup.interactable = b00l;
        canGroup.blocksRaycasts = b00l;
    }

Basically I make the buttons under the screen fader unclickable, fade in the screen fader using ‘CrossFadeAlpha’ and then set it back so it doesn’t block anything any more. I use the ‘WaitForRealSeconds’ function from this post because usually the game would be paused (eg. you go to the pause menu to then go back to the start screen).

The code in the button to activate the screen fade would look something like this:

public void goStart(){
        StartCoroutine (fadeToStart());
    }

    public IEnumerator fadeToStart(){
        getScreenFaderCode.fadeOutScreen ();
        yield return StartCoroutine(CoroutineUtil.WaitForRealSeconds(CoroutineUtil.screenFadeTime));
        Application.LoadLevel("start");
    }

I made the screenFadeTime variable inside the CoroutineUtil class since I assumed the fade time would be the same throughout. The rest is pretty standard.

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

December 2024
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
3031