Search code examples
c#unity-game-enginealpha

How to change alpha of children


in Unity I have a game object as parent and two child text-objects as children. Also there is an image child-object (three children altogether).

Now I want to change the alpha of the game-object's three children. How do I accomplish this programmatically?

I have this code but it doesn't work with text and image-objects:

public void setAlpha(float alpha) {
SpriteRenderer[] children = GetComponentsInChildren<SpriteRenderer>();
Color newColor;
foreach(SpriteRenderer child in children) {
    newColor = child.color;
    newColor.a = alpha;
    child.color = newColor;
    }
}

Solution

  • Your code would work if you were working with a SpriteRenderer.

    You can accomplish that by changing the alpha channel of the color property of the Text and Image, very similar from what you did:

    public void setAlpha(float alpha) {
        Color newColor;
    
        Image[] childrenImg = GetComponentsInChildren<Image>();
        foreach(Image img in childrenImg) {
            newColor = img.color;
            newColor.a = alpha;
            img.color = newColor;
        }
    
        Text[] childrenText = GetComponentsInChildren<Text>();
        foreach(Text text in childrenText) {
            newColor = text.color;
            newColor.a = alpha;
            text.color = newColor;
        }
    }
    

    Don't forget to include using UnityEngine.UI; on top of your script, as Text and Image are UI elements.