Skip to content

Instantly share code, notes, and snippets.

@Fallenleader
Forked from NovaSurfer/FadeInOut.cs
Last active January 30, 2016 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fallenleader/6eb7863589e276d00f0a to your computer and use it in GitHub Desktop.
Save Fallenleader/6eb7863589e276d00f0a to your computer and use it in GitHub Desktop.
Unity3D screen fading scripts (using new UI)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement.SceneManager;
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 void EndScene(int SceneNumber)
{
// Make sure the RawImage is enabled.
FadeImg.enabled = true;
// Start fading towards black.
FadeToBlack();
// If the screen is almost black...
if (FadeImg.color.a >= 0.95f)
// ... reload the level
LoadScene(SceneNumber);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment