Fading out done correctly when text changes

Hello! I am finishing a project but my fading out method seems to suck.

A fade() is called with invoke in 2 seconds after the text appears. But if the player spams E to change texts rapidly the function is called many times and it can be called as soon as another text emerges and as you understand, it disappears as soon as it appears. (I use one component for all texts).

Just tried another method (didn’t paste all the script it is huge):

    void Update()
    {
        //alpha = text.canvasRenderer.GetAlpha();

        fadetimer += Time.deltaTime;

        if (fadetimer >= 5)
        {
            Debug.Log("test");
            text.CrossFadeAlpha(1f, 2, false);
            image.CrossFadeAlpha(1f, 2, false);
        }
    }
    void OnTriggerStay2D(Collider2D other)
    {
        if (other.gameObject == player)
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                if (random < 51)
                {
                    fadetimer = 0;
                    text.canvasRenderer.SetAlpha(255f);
                    image.canvasRenderer.SetAlpha(255f);

                    text.text = "Nothing useful in here.";

With this, when fadetimer goes over 5 in the inspector, the script doesn’t stop doing the crossfade even if the timer stays under 5 for a while since it resets if I spam E. I maybe be tired after 12 hours of straight coding and not seeing something obvious here, but shouldn’t the update not get into the if and stop firing the code?

Got any (not very messy) ideas of how can I solve this problem and make it so that each time the text changes it stays for a while on the screen and then fades?

When handling fades, I suggest trying a tween engine such as LeanTween or Dotween.

However, if you have to do a fade, it’s simple. You’re going to have to have a bool that is true (isFading) when the player hits a button and then when the fade completes, it gets set to false to allow triggering again. And just check against that bool to see if you can do another fade.

1 Like