Skip to content

Instantly share code, notes, and snippets.

@JScott
Last active February 14, 2016 06:22
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 JScott/742d8a087e0aee88c9da to your computer and use it in GitHub Desktop.
Save JScott/742d8a087e0aee88c9da to your computer and use it in GitHub Desktop.
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