Unity滚动字幕—信件展示为例

思路

  1. 利用协程,逐句滚动
  2. 在每局中再利用协程,逐字滚动

代码

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LetterControl : MonoBehaviour
{
[TextArea(1, 5)] public string[] letters;//信件内容
public Text letterText;//信件展示区域

public float letterSpeed;//每行滚动速度
public float alphaSpeed;//字符滚动速度

[SerializeField]private bool isLineFinished = true;//当前行是否展示完成,最开始为true
[SerializeField] private int currentLine = 0;//当前展示的行数


// Start is called before the first frame update
void Start()
{
isLineFinished = true;
letterText.text = "旅行者:"+"\n";//初始化

StartCoroutine(ScrollingLetter());//开始展示

}

// Update is called once per frame
void Update()
{

}

private IEnumerator ScrollingLetter()
{
while(true)
{
//如果信件展示完了,加上落款并退出
if(currentLine==letters.Length && isLineFinished)
{
letterText.text += "\n";
letterText.text += "温迪";
break;
}
else//否则就展示
{
//如果当前行展示完成,启动协程函数展示下一行
if(isLineFinished)
{
isLineFinished = false;//isLineFinished设置成false
StartCoroutine(ScrollingLine(letters[currentLine++]));//传入字符串
}

yield return new WaitForSeconds(letterSpeed);//回调
}
}
}

private IEnumerator ScrollingLine(string line)
{
letterText.text += "\u00A0\u00A0\u00A0\u00A0";//段首空两格

//逐字输出
foreach (char alpha in line.ToCharArray())
{
letterText.text += alpha;
yield return new WaitForSeconds(alphaSpeed);
}

letterText.text += "\n";//换行
isLineFinished = true;//当前行输出完成后,isLineFinished设置成true
}
}

参数设置

效果