簡體   English   中英

使用協程淡入/淡出 TextMeshPro 文本元素

[英]Using coroutines to fade in/out TextMeshPro Text Element

我正在使用 TextMeshPro 設置一個“場景介紹”,其中有一些文字說“級別 1”。 我已經在畫布中創建了文本元素,我試圖找到一種方法讓它淡入,然后等待,然后淡出(有點像你在天際中發現一個新地方時看到的)。

到目前為止,我嘗試了一個通用的解決方案,因此我可以將相同的腳本用於其他用途(例如,不在場景的開頭,不僅是淡入等)。

使用 TMPro:

...
using TMPro;
...

開始和聲明:

public class IntroFade : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI textToUse;
    [SerializeField] private bool fadeIn = false;
    [SerializeField] private bool fadeOnStart = false;
    [SerializeField] private float timeMultiplier;
    private bool FadeIncomplete = false;

    private void Start()
    {

        if (fadeOnStart)
        {
            if (fadeIn)
            {
                StartCoroutine(FadeInText(timeMultiplier, textToUse));
                FadeIncomplete = true;
            }
            else
            {

                StartCoroutine(FadeOutText(timeMultiplier, textToUse));
            }
        }
    }
...

完成淡入后我想淡出的更新


    private void Update()
    {
        if (FadeIncomplete)
        {
            StartCoroutine(FadeOutText(timeMultiplier, textToUse));
        }
    }


實際衰落的Corouritnes:


private IEnumerator FadeInText(float timeSpeed, TextMeshProUGUI text)
    {
        text.color = new Color(text.color.r, text.color.g, text.color.b, 0);
        while (text.color.a < 1.0f)
        {
            text.color = new Color(text.color.r, text.color.g, text.color.b, text.color.a + (Time.deltaTime * timeSpeed));
            yield return null;
        }
    }
    private IEnumerator FadeOutText(float timeSpeed, TextMeshProUGUI text)
    {
        text.color = new Color(text.color.r, text.color.g, text.color.b, 1);
        while (text.color.a > 0.0f)
        {
            text.color = new Color(text.color.r, text.color.g, text.color.b, text.color.a - (Time.deltaTime * timeSpeed));
            yield return null;
        }
    }
    public void FadeInText(float timeSpeed = -1.0f)
    {
        if (timeSpeed <= 0.0f)
        {
            timeSpeed = timeMultiplier;
        }
        StartCoroutine(FadeInText(timeSpeed, textToUse));
    }
    public void FadeOutText(float timeSpeed = -1.0f)
    {
        if (timeSpeed <= 0.0f)
        {
            timeSpeed = timeMultiplier;
        }
        StartCoroutine(FadeOutText(timeSpeed, textToUse));
    }

所以發生的情況是它要么淡入要么淡出,這取決於首先啟動的協程。 我無法讓它淡入,在屏幕上停留 2 秒鍾,然后淡出。

我也嘗試淡入,然后創建一個協程來等待秒,然后調用淡出協程,但這也不起作用。

一個協程可以等待另一個協程的完成,這樣考慮會極大地簡化問題。 您已經創建了淡入和淡出,現在您只需要按順序運行它們,並在它們之間等待 2 秒。

private IEnumerator IntroFade (TextMeshProUGUI textToUse) {
   yield return StartCoroutine(FadeInText(1f, textToUse));
   yield return new WaitForSeconds(2f);
   yield return StartCoroutine(FadeOutText(1f, textToUse));
   //End of transition, do some extra stuff!!
}

如果您有興趣, 這些文章對於學習更多關於協程的知識非常有見地。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM