- Home /
Question by
StigC · Oct 25, 2017 at 06:38 AM ·
alphaspriterendererchildrenienumeratorover time
Fade the alpha of all childrens SpriteRenderers?
Hi there,
How do I change the alpha of all my GameObjects children over time? Well not all of them, everyone with a certain tag. Before adding the IEnumerator, I was able to turn the alpha on/off. But I'm struggling with doing it over time.
Current script looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SeeThroughObjects : MonoBehaviour {
private Color startColor;
private Color transparentColor;
private void Start()
{
foreach (SpriteRenderer sr in GetComponentsInChildren<SpriteRenderer>())
{
startColor = sr.material.color;
}
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Player")
{
foreach (SpriteRenderer sr in GetComponentsInChildren<SpriteRenderer>())
{
if (sr.CompareTag("HiddenSprite")) //If It's an object tagged with HiddenSprite, leave as is.
{
sr.material.color = startColor;
}
else //Make all children that are NOT tagged with Hiddensprite transparent.
{
//sr.material.color = transparentColor;
StartCoroutine(FadeTo(0.0f, 1.0f));
}
}
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Player")
{
foreach (SpriteRenderer sr in GetComponentsInChildren<SpriteRenderer>())
{
if (sr.CompareTag("HiddenSprite")) //If It's an object tagged with HiddenSprite, leave as is.
{
sr.material.color = startColor;
}
else //Make all children that are NOT tagged with Hiddensprite visible again.
{
//sr.material.color = startColor;
StartCoroutine(FadeTo(1.0f, 1.0f));
}
}
}
}
IEnumerator FadeTo(float aValue, float aTime)
{
float alpha = startColor.a;
for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / aTime)
{
transparentColor = new Color(1, 1, 1, Mathf.Lerp(alpha, aValue, t));
startColor = transparentColor;
yield return null;
}
}
}
Thanks in advance!
Comment
What is not working?
And why are you assigning startColor in a for loop? Obviously only the last Sprite Renderer of the iteration will be assigned to start color, and everything before the last one will be ignored.