2016年1月9日 星期六

Unity:遊戲對話框打字機特效

一般在遊戲對話框中,為了不讓對話框文字太死板,會讓文字有打字機的特效.

我們這篇使用協程來實現
程式碼如下


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
 
public class TypewriterText : MonoBehaviour
{
 
    private float letterPause = 0.2f;
    [SerializeField] private AudioClip typeSound;
    [SerializeField] private Text txtDisplay;
    private string words;
    private string text = "Welcome to summerRift!!";
 
 
    public IEnumerator display(string displayStr)
    {
        words = displayStr;
        text = "";
        yield return new WaitForSeconds(2f);
        StartCoroutine(TypeText());
    }
 
 void Start ()
 {
     StartCoroutine(display(text));
 
 }
 
    // 開啟打字效果
    private IEnumerator TypeText()
    {
        foreach (var word in words)
        {
            txtDisplay.text += word;
            yield return new WaitForSeconds(letterPause);
        }
                  
    }
}

這個腳本可以提供給需要打字的文字框

沒有留言:

張貼留言