Last active
February 14, 2016 06:22
-
-
Save JScott/742d8a087e0aee88c9da to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class CustomFader : MonoBehaviour { | |
private Material screenMaterial; | |
public bool startFaded = true; | |
public float fadeSpeed = 0.5f; | |
void Awake() { | |
screenMaterial = GetComponent<Renderer>().material; | |
SetAlphaTo(startFaded ? 1f : 0f); | |
} | |
private bool ActuallyFaded() { | |
return screenMaterial.color.a == 1f; | |
} | |
private bool Fading() { | |
return screenMaterial.color.a != 0f && screenMaterial.color.a != 1f; | |
} | |
public void ToggleFade() { | |
if (!Fading()) { | |
float target = ActuallyFaded() ? 0f : 1f; | |
StartCoroutine(FadeTo(target)); | |
} | |
} | |
private IEnumerator FadeTo(float target) { | |
float progress = 0f; | |
float start = screenMaterial.color.a; | |
while (screenMaterial.color.a != target) { | |
yield return new WaitForEndOfFrame(); | |
float newAlpha = Mathf.Lerp(start, target, progress); | |
SetAlphaTo(newAlpha); | |
progress += fadeSpeed * Time.deltaTime; | |
} | |
} | |
private void SetAlphaTo(float value) { | |
Color newColor = screenMaterial.color; | |
newColor.a = value; | |
screenMaterial.color = newColor; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment