Home > Mobile >  Fade out images in order
Fade out images in order

Time:11-17

Is basically a mathematical question, would like to know what would be a good solution.

Problem: I have 25 images placed in one line. I want the images to fade out in the order. That is the first image should be completely opaque and last image should be completely transparent. I have placed all these images in an order inside one parent.

My solution: I am just providing a fixed number that iterates itself for the alpha.

What I am looking for: a formula so that this "fixed" number can be dynamically changed by number of images present.

void Start () {

        int color = 10; //my fixed number

        foreach (Transform child in transform) {

                child.gameObject.GetComponent<Image>().color = new Color32(255, 255, 255, (byte) (255 - color));
                color  = 10; //iterating for the next child
            }
  }

CodePudding user response:

What about simply calculating the step:

void Start () 
{
    if(transform.childCount <= 1)
    {
        Debug.LogWarning("Requires at least 2 children!");
        return;
    }

    var alphaStep = 1f / (transform.childCount - 1);
    var alpha = 1f;
    foreach (Transform child in transform) 
    {
        child.GetComponent<Image>().color = new Color(1f, 1f, 1f, alpha);
        alpha -= alphaStep;     
    }
}

Or if you want full control over the maximum and minimum alpha you could use e.g.

public float minAlpha = 0f;
public float maxAlpha = 1f;

and then

var alphaStep = 1f / (transform.childCount - 1);
for (var i = 0; i < transform.childCount; i  ) 
{
    var factor = i / (transform.childCount - 1);
    transform.GetChild(i).GetComponent<Image>().color = new Color(1f, 1f, 1f, Mathf.Lerp(maxAlpha, minAlpha, factor));    
}

CodePudding user response:

I would recomend use an Array to iterate through your elements more freely.

With that you could go something like... (coding in SO, not tested)

Image[] images; //this should reference the array constructed elsewhere where you load the images.

private void Start() {
    for (int i = 0; i < images.Length; i  ) {
        int alpha = 255 - (Mathf.CeilToInt(255 / images.Length) * i   1);
        images[i].color = Color32(255,255,255,alpha);}
}

That will probably do what you want.

By the way, not shure why you using Color32 but working with "float" RGBA will rid you from that ceil and give you more precission.

  • Related