[Unity 4.6 UI] How to fade a Canvas Group in and then out after a seconds?

Hiya! I’m somewhat new to coding and I recently just figured out how to make a fade in effect on my Canvas Group thingy and now I’ve been doing trial and errors for almost an hour now and I can’t figure out how to fade it out after a seconds.

This is the fade in code I made:

using UnityEngine;
using System.Collections;

public class CanvasFadeInAndOut : MonoBehaviour {
    CanvasGroup csGrp;
   
    void Awake(){
        csGrp = GetComponent<CanvasGroup>();
    }
   
    void Start (){
        StartCoroutine("FadeIn");
    }

    IEnumerator FadeIn(){
        csGrp.alpha = 0;
        float time = 5f;
       
        while(csGrp.alpha < 1){
            csGrp.alpha += Time.deltaTime / time;
            yield return null;
        }
    }
}

What do I have to add to have a fade out effect after a few seconds of fading in?

Bump!

Would love some help soon. I still can’t figure it out XD…

;-; welp…

I just want to say that your script above helped me with my wish to fade in my canvas group. :slight_smile:

Sorry you didn’t manage to get fading out to work after the fade in. Maybe we can work something out together. If you’re still around…

you could do something like this

using UnityEngine;
using System.Collections;

public class CGFade : MonoBehaviour {
    private CanvasGroup _canvasGroup;
    [SerializeField] private float _duration = 3f;

    private void Awake() {
        _canvasGroup = GetComponent<CanvasGroup>();
    }

    private void Start() {
        StartCoroutine(FadeCGAlpha(0f, 1f, _duration));
    }

    private IEnumerator FadeCGAlpha(float from, float to, float duration) {
        float elaspedTime = 0f;
        while (elaspedTime <= duration) {
            elaspedTime += Time.deltaTime;
            _canvasGroup.alpha = Mathf.Lerp(from, to, elaspedTime / duration);
            yield return null;
        }
        _canvasGroup.alpha = to;
    }
}