Unity游戏对话系统:如何立即跳过/结束协程?
解决方案:点击跳过逐字对话动画
要实现点击屏幕跳过逐字显示、直接展示完整对话的需求,你可以通过跟踪当前运行的协程实例,在点击时终止协程并直接设置完整文本,同时调整交互逻辑区分「跳过动画」和「切换对话」两种场景。具体修改步骤如下:
1. 添加协程引用变量
在脚本中新增一个变量,专门跟踪当前正在运行的逐字显示协程,避免用StopAllCoroutines()误杀其他协程:
// 在InformantDialogue类中添加 private Coroutine currentTypingCoroutine;
2. 修改逐字显示协程
让协程在完成逐字动画后才允许点击切换对话,同时确保协程结束后清空引用:
IEnumerator TypeSentence(string sentence) { dialogue.text = ""; foreach(char letter in sentence.ToCharArray()) { dialogue.text += letter; yield return new WaitForSeconds(0.01f); } // 逐字显示完成后,允许点击切换对话 clickEnable = true; // 清空协程引用 currentTypingCoroutine = null; }
3. 调整协程启动逻辑
在启动逐字协程前,先停止之前的协程,并设置clickEnable为false(逐字显示过程中,点击优先触发跳过而非切换):
public void loadCharacterData() { // DIALOGUE multiDialog = getIDialog(dialogId).dialog_message.Split('#'); if (multiDialogCycle == 4) { article.SetActive(true); } string targetText; if (multiDialog.Length == 1) { targetText = getIDialog(dialogId).dialog_message; } else if (multiDialogCycle < multiDialog.Length) { targetText = multiDialog[multiDialogCycle]; } else { return; } // 停止当前正在运行的逐字协程 if (currentTypingCoroutine != null) { StopCoroutine(currentTypingCoroutine); } // 启动新协程并保存引用 currentTypingCoroutine = StartCoroutine(TypeSentence(targetText)); // 逐字显示中,暂时禁止切换对话(点击会触发跳过) clickEnable = false; }
4. 更新点击交互逻辑
在Update()中区分两种点击场景:如果正在逐字显示,就跳过动画展示完整文本;如果已经显示完成,就执行切换对话的逻辑:
void Update() { if (Input.GetMouseButtonDown(0)) { // 场景1:正在逐字显示,点击跳过动画 if (currentTypingCoroutine != null) { StopCoroutine(currentTypingCoroutine); currentTypingCoroutine = null; // 直接设置完整对话文本 string targetText = multiDialog.Length == 1 ? getIDialog(dialogId).dialog_message : multiDialog[multiDialogCycle]; dialogue.text = targetText; // 允许后续点击切换对话 clickEnable = true; return; } // 场景2:已显示完整对话,点击切换或关闭 if (clickEnable) { Debug.Log(dialogId); if (multiDialog.Length > 1) { if (multiDialogCycle == multiDialog.Length - 1) { closeDialog(); progressDialog(); } else { multiDialogCycle++; loadCharacterData(); } } else { closeDialog(); progressDialog(); } } } }
5. 清理协程引用
在关闭对话框时,确保停止并清空协程引用,避免残留:
private void closeDialog() { dialogBox.SetActive(false); clickEnable = false; multiDialogCycle = 0; // 清理协程 if (currentTypingCoroutine != null) { StopCoroutine(currentTypingCoroutine); currentTypingCoroutine = null; } }
这样修改后,用户在逐字动画播放时点击屏幕,会立即终止动画并显示完整对话;再次点击则会切换到下一段对话或关闭对话框,完全符合需求。
内容的提问来源于stack exchange,提问作者Ledjoric Libiran
相关产品推荐
相关产品推荐

