0

fade out/in

I tried to add a canvas group to the canvas and then change the canvas group alpha to 0 but it didn't do anything.

I tried it first with a cube dragged all children under a cube added a new material to the cube change the material Rendering Mode to Fade then changed the alpha color to 0 so the cube is faded out but not the children.

If i just disable the canvas the canvas and its children will be gone but that's not fading effect.

What i want to do is to fade out/in the canvas and its children through a script but for first it's not working in the editor.

Daniel Lip
  • 3,867
  • 7
  • 58
  • 120

1 Answers1

0

In fact, The Alpha system is different for various objects, and what you need is a single script that changes each object according to its specific component. Keep in mind that the Canvas Group can only cover UI elements, and zeroing one material parameters on parent object, doesn't effect on children's material. To solve the problem, this script will help you manage alpha from some different objects. Copy this and paste in the .cs file according to the class name: AlphaGroup.

using System.Collections.Generic;
using UnityEngine;
public class AlphaGroup : MonoBehaviour
{
    [Range(0, 1)]
    public float alpha = 1f;

    public float Alpha
    {
        get => alpha;
        set
        {
            alpha = value;
            
            UIGroup.alpha = alpha; // setup CanvasGroup Alpha

            SetMaterialsAlpha(materials);
            
            foreach (var _meshRenderer in MeshRenderers) // for all mesh renderer materials
            {
                if (!_meshRenderer) continue;
                SetMaterialsAlpha(_meshRenderer.materials);
            }
            
            foreach (var _sprite in Sprites) // setup sprites
            {
                if (!_sprite) continue;
                var col = _sprite.color;
                col.a = alpha;
                _sprite.color = col;
            }
        }
    }
    private void SetMaterialsAlpha(IEnumerable<Material> _materials)
    {
        foreach (var material in _materials)
        {
            if (!material) continue;
            var col = material.color;
            col.a = alpha;
            material.color = col;
        }
    }
    public void OnValidate() => Alpha = alpha;

    [Header("Your Canvas Group")]
    public CanvasGroup UIGroup;

    [Header("Your Sprites")]
    public SpriteRenderer[] Sprites;
    
    [Header("Your Mesh Renderers")]
    public MeshRenderer[] MeshRenderers;

    [Header("Your materials")]
    public Material[] materials;
}
KiynL
  • 4,097
  • 2
  • 16
  • 34