Another Fade Script in C#

Introduction

Hello everybody! I was looking for an easy way to fade the screen and found this page. The scripts here didn't do quite what I wanted, so I rewrote the C# version. This one will fade from any color to any color. Usage: use "SetScreenOverlayColor" to set the initial color, then use "StartFade" to set the target color and the fade duration (in seconds) and start the fade.

Source (CameraFade.cs)

// simple fading script// A texture is stretched over the entire screen. The color of the pixel is set each frame until it reaches its target color.usingUnityEngine;publicclass CameraFade : MonoBehaviour
{private GUIStyle m_BackgroundStyle =new GUIStyle();// Style for background tilingprivate Texture2D m_FadeTexture;// 1x1 pixel texture used for fadingprivate Color m_CurrentScreenOverlayColor =new Color(0,0,0,0);// default starting color: black and fully transparrentprivate Color m_TargetScreenOverlayColor =new Color(0,0,0,0);// default target color: black and fully transparrentprivate Color m_DeltaColor =new Color(0,0,0,0);// the delta-color is basically the "speed / second" at which the current color should changeprivateint m_FadeGUIDepth =-1000;// make sure this texture is drawn on top of everything// initialize the texture, background-style and initial color:privatevoid Awake(){
m_FadeTexture =new Texture2D(1, 1);
m_BackgroundStyle.normal.background= m_FadeTexture;
SetScreenOverlayColor(m_CurrentScreenOverlayColor);// TEMP:// usage: use "SetScreenOverlayColor" to set the initial color, then use "StartFade" to set the desired color & fade duration and start the fade//SetScreenOverlayColor(new Color(0,0,0,1));//StartFade(new Color(1,0,0,1), 5);}// draw the texture and perform the fade:privatevoid OnGUI(){// if the current color of the screen is not equal to the desired color: keep fading!if(m_CurrentScreenOverlayColor != m_TargetScreenOverlayColor){// if the difference between the current alpha and the desired alpha is smaller than delta-alpha * deltaTime, then we're pretty much done fading:if(Mathf.Abs(m_CurrentScreenOverlayColor.a- m_TargetScreenOverlayColor.a)< Mathf.Abs(m_DeltaColor.a)* Time.deltaTime){
m_CurrentScreenOverlayColor = m_TargetScreenOverlayColor;
SetScreenOverlayColor(m_CurrentScreenOverlayColor);
m_DeltaColor =new Color(0,0,0,0);}else{// fade!
SetScreenOverlayColor(m_CurrentScreenOverlayColor + m_DeltaColor * Time.deltaTime);}}// only draw the texture when the alpha value is greater than 0:if(m_CurrentScreenOverlayColor.a>0){
GUI.depth= m_FadeGUIDepth;
GUI.Label(new Rect(-10, -10, Screen.width+10, Screen.height+10), m_FadeTexture, m_BackgroundStyle);}}// instantly set the current color of the screen-texture to "newScreenOverlayColor"// can be usefull if you want to start a scene fully black and then fade to opaguepublicvoid SetScreenOverlayColor(Color newScreenOverlayColor){
m_CurrentScreenOverlayColor = newScreenOverlayColor;
m_FadeTexture.SetPixel(0, 0, m_CurrentScreenOverlayColor);
m_FadeTexture.Apply();}// initiate a fade from the current screen color (set using "SetScreenOverlayColor") towards "newScreenOverlayColor" taking "fadeDuration" secondspublicvoid StartFade(Color newScreenOverlayColor, float fadeDuration){if(fadeDuration <= 0.0f)// can't have a fade last -2455.05 seconds!{
SetScreenOverlayColor(newScreenOverlayColor);}else// initiate the fade: set the target-color and the delta-color{
m_TargetScreenOverlayColor = newScreenOverlayColor;
m_DeltaColor =(m_TargetScreenOverlayColor - m_CurrentScreenOverlayColor)/ fadeDuration;}}}</csharp>== C# ===== Introduction ===
Author:[[User:ratmat2000|ratmat2000]]
Extended version written in C# (put it into "Standard Assets/Scripts" to use it from within JavaScript files).This version is identical to the Boo version but written in C#.=== Source (CameraFade.cs)===<javascript>usingUnityEngine;publicclass CameraFade : MonoBehaviour
{// ---------------------------------------- // PUBLIC FIELDS// ----------------------------------------// Alpha start valuepublicfloat startAlpha =1;// Texture used for fadingpublic Texture2D fadeTexture;// Default time a fade takes in secondspublicfloat fadeDuration =2;// Depth of the gui elementpublicint guiDepth =-1000;// Fade into scene at startpublicbool fadeIntoScene =true;// ---------------------------------------- // PRIVATE FIELDS// ----------------------------------------// Current alpha of the textureprivatefloat currentAlpha =1;// Current duration of the fadeprivatefloat currentDuration;// Direction of the fadeprivateint fadeDirection =-1;// Fade alpha toprivatefloat targetAlpha =0;// Alpha differenceprivatefloat alphaDifference =0;// Style for background tilingprivate GUIStyle backgroundStyle =new GUIStyle();private Texture2D dummyTex;// Color object for alpha setting
Color alphaColor =new Color();// ---------------------------------------- // FADE METHODS// ----------------------------------------publicvoid FadeIn(float duration, float to){// Set fade duration
currentDuration = duration;// Set target alpha
targetAlpha = to;// Difference
alphaDifference = Mathf.Clamp01(currentAlpha - targetAlpha);// Set direction to Fade in
fadeDirection =-1;}publicvoid FadeIn(){
FadeIn(fadeDuration, 0);}publicvoid FadeIn(float duration){
FadeIn(duration, 0);}publicvoid FadeOut(float duration, float to){// Set fade duration
currentDuration = duration;// Set target alpha
targetAlpha = to;// Difference
alphaDifference = Mathf.Clamp01(targetAlpha - currentAlpha);// Set direction to fade out
fadeDirection =1;}publicvoid FadeOut(){
FadeOut(fadeDuration, 1);}publicvoid FadeOut(float duration){
FadeOut(duration, 1);}// ---------------------------------------- // STATIC FADING FOR MAIN CAMERA// ----------------------------------------publicstaticvoid FadeInMain(float duration, float to){
GetInstance().FadeIn(duration, to);}publicstaticvoid FadeInMain(){
GetInstance().FadeIn();}publicstaticvoid FadeInMain(float duration){
GetInstance().FadeIn(duration);}publicstaticvoid FadeOutMain(float duration, float to){
GetInstance().FadeOut(duration, to);}publicstaticvoid FadeOutMain(){
GetInstance().FadeOut();}publicstaticvoid FadeOutMain(float duration){
GetInstance().FadeOut(duration);}// Get script fom Camerapublicstatic FadeInOut GetInstance(){// Get Script
FadeInOut fader =(FadeInOut)Camera.main.GetComponent("FadeInOut");// Check if script existsif(fader ==null){
Debug.LogError("No FadeInOut attached to the main camera.");}return fader;}// ---------------------------------------- // SCENE FADEIN// ----------------------------------------publicvoid Start(){
Debug.Log("Starting FadeInOut");
dummyTex =new Texture2D(1,1);
dummyTex.SetPixel(0,0,Color.clear);
backgroundStyle.normal.background= fadeTexture;
currentAlpha = startAlpha;if(fadeIntoScene){
FadeIn();}}// ---------------------------------------- // FADING METHOD// ----------------------------------------publicvoid OnGUI(){// Fade alpha if activeif((fadeDirection ==-1&& currentAlpha > targetAlpha)||(fadeDirection ==1&& currentAlpha < targetAlpha)){// Advance fade by fraction of full fade time
currentAlpha +=(fadeDirection * alphaDifference)*(Time.deltaTime/ currentDuration);// Clamp to 0-1
currentAlpha = Mathf.Clamp01(currentAlpha);}// Draw only if not transculentif(currentAlpha >0){// Draw texture at depth
alphaColor.a= currentAlpha;
GUI.color= alphaColor;
GUI.depth= guiDepth;
GUI.Label(new Rect(-10, -10, Screen.width+10, Screen.height+10), dummyTex, backgroundStyle);}}}</javascript>
The following bugs have been identified in the code segment above
LINE 133: FadeInOut should read CameraFade
LINE 136: Replace FadeInOut occurances with CameraFade
Also when I was trying to use it, if I didn't FadeIn on start the value for currentAlpha would end up NaN. I had to do some rearranging, but when I was done there were conditions that would cause currentAlpha to equal the targetAlpha when I issued a FadeIn command. I corrected this by placing the following code in the FadeIn method and an equivalent one in the FadeOut.
<javascript>
//Check to see if currentAlpha is set to 1. It will need to be 1 to fade properly
if (currentAlpha != 1){
currentAlpha = 1;
}
</javascript>
I would replace this code with mine, but I've already changed my so much I am hesitant to do so, I'll leave that exercise to someone else.
[[Category: JavaScript]]
[[Category: Boo]]
[[Category: Scripts]]
[[Category: Camera]]