iT邦幫忙

2021 iThome 鐵人賽

DAY 26
0
自我挑戰組

用unity製作2DRPG雛形-沒有大野狼的小紅帽系列 第 26

26.unity打字機(StartCoroutine)

  • 分享至 

  • twitterImage
  •  

實現打字機功能:字出現之間會有時差,讓一個字接一個字出現。

迴圈{

	 //畫面texe += 清單[第一件][第幾個字]
	ui.text += textList[textIndex][letter];
	letter++;
	時間差;

}

要在unity中製造時間差,除了Timer.deltaTime就是使用Coroutine協程搭配WaitForSeconds()!

Coroutine協程(參考手冊)

可以將Coroutine協程當作一個突發事件,能夠在不影響主程式的情況下執行一段程式碼,等待秒數或完成條件之後才繼續往下執行程式碼。

在unity中要開始一個協程(Starts a Coroutine),使用StartCoroutine()

宣告定義

public Coroutine StartCoroutine(IEnumerator routine);

使用方式

寫一個IEnumerator 方法(),裡面必須包含yield return,yield return會告訴主線程式繼續執行主線程式。

IEnumerator 方法名稱()
{
	//執行事情(主程式繼續執行前)
	//程式執行到yield return時會繼續在主程式中執行
	yield return new WaitForSeconds(秒數);
	//不一定要回傳等待秒數,也可以是null或數字或其他條件形式。
	//執行事情(主程式繼續執行後)
}

官方案例

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(coroutineA());
    }

    IEnumerator coroutineA()
    {
        // wait for 1 second
        Debug.Log("coroutineA created");
        yield return new WaitForSeconds(1.0f);
        yield return StartCoroutine(coroutineB());
        Debug.Log("coroutineA running again");
    }

    IEnumerator coroutineB()
    {
        Debug.Log("coroutineB created");
        yield return new WaitForSeconds(2.5f);
        Debug.Log("coroutineB enables coroutineA to run");
    }
}

打字機

IEnumerator SetTextUI()
    {
        int letter = 0;
        while(!cancelTyping && letter < textList[textIndex].Length -1)
        {
            uiText.text += textList[textIndex][letter];
            letter++;
            yield return new WaitForSeconds(textSpeed);
        }
        uiText.text = textList[textIndex];
        cancelTyping = false;
        textFinished = true;
        textIndex++;
        
    }

上一篇
25.unity動態加載(Resources.Load)
下一篇
27.unity換圖片表情
系列文
用unity製作2DRPG雛形-沒有大野狼的小紅帽30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言