Last active
November 6, 2021 17:02
-
-
Save unitycoder/4a2c8e1be0eef6d95146 to your computer and use it in GitHub Desktop.
UI Image and Text color fade
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
/* Fade all current object anc child images & texts, code needs cleaning up.. */ | |
using UnityEngine; | |
using System.Collections; | |
using UnityEngine.UI; | |
public class UIFadeEffect : MonoBehaviour | |
{ | |
public bool destroyRootAfterFade=false; | |
void Start () { | |
StartCoroutine(Fade(fadeSpeed)); | |
} | |
IEnumerator Fade(float duration) | |
{ | |
var images = GetComponentsInChildren<Image>(); | |
var texts = GetComponentsInChildren<Text>(); | |
Color[] origImageColors = new Color[images.Length]; | |
Color[] origImageColorsEnd = new Color[images.Length]; | |
Color[] origTextColors = new Color[texts.Length]; | |
Color[] origTextColorsEnd = new Color[texts.Length]; | |
int j = 0; | |
foreach (var item in images) { | |
origImageColors[j] = images[j].color; | |
origImageColorsEnd[j] = new Color(images[j].color.r,images[j].color.g,images[j].color.b,0); | |
j++; | |
} | |
j = 0; | |
foreach (var item in texts) { | |
origTextColors[j] = texts[j].color; | |
origTextColorsEnd[j] = new Color(texts[j].color.r,texts[j].color.g,texts[j].color.b,0); | |
j++; | |
} | |
for (float timer = 0; timer < duration; timer += Time.deltaTime) | |
{ | |
for (int i = 0; i < images.Length; i++) | |
{ | |
if (images.Length>=i) images[i].color = Color.Lerp(origImageColors[i],origImageColorsEnd[i],timer/duration); | |
if (texts.Length>=i) texts[i].color =Color.Lerp(origTextColors[i],origTextColorsEnd[i],timer/duration); | |
} | |
yield return 0; | |
} | |
if (destroyRootAfterFade) Destroy(gameObject.transform.root.gameObject); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment