Unity对话代码无法逐字符输出文本问题求助
Unity对话逐字显示失效问题修复
你的代码核心问题出在Update方法的逻辑上——只要没有点击鼠标左键,每一帧都会执行StopAllCoroutines()并直接把整行文本赋值给textComp,刚启动的TypeLine协程还没来得及逐字输出就被强制终止,自然看不到逐字动画。
修复方案
把“跳过动画直接显示整行”的逻辑,改成只有在点击左键且当前文本还没完全显示的时候才触发,而非每一帧都执行。
修正后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class Dialogue : MonoBehaviour { public TextMeshProUGUI textComp; public string[] lines; public float textspeed; private int index; void Start() { textComp.text = string.Empty; startDialogue(); } void Update() { if (Input.GetMouseButtonDown(0)) { // 当前文本已完全显示,切换到下一行 if (textComp.text == lines[index]) { NextLine(); } // 仍在逐字显示,跳过动画直接展示完整内容 else { StopAllCoroutines(); textComp.text = lines[index]; } } } void startDialogue() { index = 0; StartCoroutine(TypeLine()); } IEnumerator TypeLine() { foreach (char c in lines[index].ToCharArray()) { textComp.text += c; yield return new WaitForSeconds(textspeed); } } void NextLine() { if (index < lines.Length - 1) { index++; textComp.text = string.Empty; StartCoroutine(TypeLine()); } else { gameObject.SetActive(false); } } }
关键修改说明
- 移除了原
Update方法中无意义的else分支,将“跳过动画”的逻辑整合到左键点击的判断流程内 - 现在仅在主动点击左键时,才会根据当前文本状态执行对应操作,不会在无操作时强制终止协程
内容的提问来源于stack exchange,提问作者Cactys
相关产品推荐
相关产品推荐

