Skip to content

Instantly share code, notes, and snippets.

@NovaSurfer
Last active February 5, 2022 15:59
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save NovaSurfer/5f14e9153e7a2a07d7c5 to your computer and use it in GitHub Desktop.
Save NovaSurfer/5f14e9153e7a2a07d7c5 to your computer and use it in GitHub Desktop.
Unity3D screen fading script (using new UI)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
public class ScreenFader : MonoBehaviour
{
public Image FadeImg;
public float fadeSpeed = 1.5f;
public bool sceneStarting = true;
void Awake()
{
FadeImg.rectTransform.localScale = new Vector2(Screen.width, Screen.height);
}
void Update()
{
// If the scene is starting...
if (sceneStarting)
// ... call the StartScene function.
StartScene();
}
void FadeToClear()
{
// Lerp the colour of the image between itself and transparent.
FadeImg.color = Color.Lerp(FadeImg.color, Color.clear, fadeSpeed * Time.deltaTime);
}
void FadeToBlack()
{
// Lerp the colour of the image between itself and black.
FadeImg.color = Color.Lerp(FadeImg.color, Color.black, fadeSpeed * Time.deltaTime);
}
void StartScene()
{
// Fade the texture to clear.
FadeToClear();
// If the texture is almost clear...
if (FadeImg.color.a <= 0.05f)
{
// ... set the colour to clear and disable the RawImage.
FadeImg.color = Color.clear;
FadeImg.enabled = false;
// The scene is no longer starting.
sceneStarting = false;
}
}
public IEnumerator EndSceneRoutine(int SceneNumber)
{
// Make sure the RawImage is enabled.
FadeImg.enabled = true;
do
{
// Start fading towards black.
FadeToBlack();
// If the screen is almost black...
if (FadeImg.color.a >= 0.95f)
{
// ... reload the level
SceneManager.LoadScene(SceneNumber);
yield break;
}
else
{
yield return null;
}
} while (true);
}
public void EndScene(int SceneNumber)
{
sceneStarting = false;
StartCoroutine("EndSceneRoutine", SceneNumber);
}
}
using UnityEngine;
using System.Collections;
public class LevelChanger : MonoBehaviour {
ScreenFader fadeScr;
public int SceneNumb;
void Awake()
{
fadeScr = GameObject.FindObjectOfType<ScreenFader>();
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Player")
{
fadeScr.EndScene(SceneNumb);
}
}
}
@kurikuri0608
Copy link

Hi would love to use this script but somehow it is not working. Is there any example scenes you can provide to see how you structured it please.

@NovaSurfer
Copy link
Author

NovaSurfer commented Apr 26, 2015

Hello, thank you for asking!

Firstly:

  1. Create a new Image.
    (location in the scene is not important, the size too)
  2. Attach the script to any GameObject (mine is MainCamera).
  3. Specify our Image (Fade Img).

Secondly:
You must call EndScene() method from another script when you need it.

Example:

using UnityEngine;
using System.Collections;

public class LevelChanger : MonoBehaviour {

    ScreenFader fadeScr;
    public int SceneNumb;

    void Awake()
    {
        fadeScr = GameObject.FindObjectOfType<ScreenFader>();
    }

    void OnTriggerEnter(Collider col)
    {
        if (col.gameObject.tag == "Player")
        {
            fadeScr.EndScene(SceneNumb);
        }
    }
}
  1. Create a new script LevelChanger
    (This script works only with 3D, because it uses a method OnTriggerEnter)
  2. Attach this script to invisible mesh.
    (gameObject must have a collider component with enabled trigger)
  3. Enter a variable ** SceneNumb **, which is responsible for the number of loading scene

P.S. My english is not very good, sorry 😄

@vladimirigorevitch
Copy link

Hi, thanks for a script. My FadeImg object disappears from the scene right after I launch the game, but a script changes its color in the Inspector. Any idea why is it disappear? Image object is last in UI hierarchy.

@Fallenleader
Copy link

do note that Application.LoadLevel(SceneNumber); has been depreciated and replaced with UnityEngine.SceneManagement.SceneManager.LoadScene(SceneNumber);

Also, adding "using UnityEngine.SceneManagement.SceneManager;" will cut this extra typing later on

@NovaSurfer
Copy link
Author

Edited, thank you.

@Fallenleader
Copy link

I have also noted that this can break when using prefabs of the canvas, and also seems to be costly in performance, generating serious lag. Not exactly sure why, as the image used was as low a quality as one could possibly have, and the prefab of the canvas was identical to the original.

@natnapil
Copy link

why is it Fade fadeScr;?

The type or namespace name `Fade' could not be found. Are you missing a using directive or an assembly reference?

@NovaSurfer
Copy link
Author

Woops, its for previous version
use ScreenFader fadeScr;
I changed my second comment, thank you

@HendrysTobar
Copy link

I think you should make "EndScene" stub method that starts a CoRoutine (EndSceneCoRoutine), this way you will be able to call EndScene from another script and the fading out will start.
As it is now, it will only decrease the curtain's darkness a little but nothing else:

I did this:

public void EndScene(int SceneNumber)
    {
        sceneStarting = false;
        StartCoroutine("EndSceneRoutine", SceneNumber);
    }

    public IEnumerator EndSceneRoutine(int SceneNumber)
    {
        // Make sure the RawImage is enabled.

        FadeImg.enabled = true;
        do
        {
            // Start fading towards black.
            FadeToBlack();

            // If the screen is almost black...
            if (FadeImg.color.a >= 0.95f)
            {
                // ... reload the level
                SceneManager.LoadScene(SceneNumber);
                yield break;
            }
            else
            {
                yield return null;
            }
        }while (true);


    }

How do you create a Pull request in Gist? Is it possible?

@shaneparsons
Copy link

shaneparsons commented May 31, 2016

@NovaSurfer I don't understand the following implementation code

using UnityEngine;
using System.Collections;

public class nextLevel : MonoBehaviour {
    ScreenFader fadeScr;
    public int SceneNumb;

    void Start(){
        fadeScr = GameObject.FindObjectOfType<Fade>();
    }

    void OnTriggerStay2D(Collider2D col){
        if(col.gameObject.tag == "Player"){
            fadeScr.EndScene(SceneNumb);
        }
    }
}

ScreenFader fadeScr; and <Fade> are giving me errors as well... Is there an easier way to trigger the function, say from a button?

@NovaSurfer
Copy link
Author

@shaneparsons, hi check out new revision. I updated the script and added an example

@rabihh
Copy link

rabihh commented Aug 18, 2016

hello, i'm trying to call the function EndScene(SceneNumb) from another script but it gives me an error ( NullReferenceException: Object reference not set to an instance of an object
StartMenu.StartLevel () (at Assets/Scripts/StartMenu.cs:130)
UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:153)
UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:630)
UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:765)
UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:53)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:52)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler](UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:269)
UnityEngine.EventSystems.EventSystem:Update())

can you help me please ?

@xudz
Copy link

xudz commented Aug 11, 2017

Awesome stuff! But I'm curious, why do you not disable the image after the fade is over, for efficiency's sake?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment