简体   繁体   中英

How to fade text in Unity

Heyo, I'm trying to make my GUI fade when not in use. Specifically, for a Minecraft-style tool bar, I want it to pop in when a player uses the scroll wheel and fade away in a few seconds after they're done scrolling. The GUI is working perfectly, but I can't get this fading thing to work. I assume once I get the selection text working, the sprites will follow easily, so I'll just talk about the selection text for now. The inventoryText starts the game at full white.

protected void OnGUI()
{
    if (isInvGUIDirty)
    {
        // Update selection text
        controllerInterface.inventoryText.CrossFadeAlpha(255f, 0, false);
        controllerInterface.inventoryText.CrossFadeAlpha(0.1f, 2, false);

^ This results (when I move the scrollwheel) in the inventory text going full-white, and two seconds later shifting to a light grey. There is no sleek transition, and it is still clearly visible. This repeats every time I move the scrollwheel.

controllerInterface.inventoryText.CrossFadeAlpha(255f, 0, false);
controllerInterface.inventoryText.CrossFadeAlpha(0f, 2, false);

^ This results (when I move the scrollwheel) in the inventory text going full-white, and two seconds later shifting to invisible. This repeats every time I move the scrollwheel. Apparently 0.1 alpha makes all the difference o_O

controllerInterface.inventoryText.color = Color.white;
controllerInterface.inventoryText.CrossFadeAlpha(0.1f, 2, false);

^ This results in the inventory text slowly fading to a light grey, but no change on scrollwheel.

Any ideas on why CrossFadeAlpha() isn't working as expected?

Sorry, wasn't getting email updates from here :/. So what I ended up doing that worked was to write my own coroutine at the most basic level, which seemed to work...for some reason. Honestly, not sure why the previous didn't work. This operates on a CanvasGroup instead of the individual items too.

    private void FadeInventoryGroup(float alpha, float delay)
    {
        if (fader != null)
            StopCoroutine(fader);

        fader = StartCoroutine(EFadeOutInventory(alpha, delay));
    }

    private IEnumerator EFadeOutInventory(float alpha, float delay)
    {
        yield return new WaitForSeconds(delay);

        float progress = 1f - Mathf.Abs(inventoryGroup.alpha - alpha);
        float start = inventoryGroup.alpha;
        while (progress < 1f)
        {
            progress += Time.deltaTime;
            inventoryGroup.alpha = Mathf.Lerp(start, alpha, progress);
            yield return 0;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM