You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中基于Queue实现对话回退功能的技术求助

基于Queue实现Unity对话回退的解决方案

因为Queue本身是先进先出的结构,无法直接回溯已取出的元素,我们可以新增一个**栈(Stack)**来存储已经显示过的对话内容,同时记录当前正在显示的对话,以此实现回退功能,完全不需要修改原有的Queue数据结构。

1. 新增必要的成员变量

在DialogueManager类中添加两个变量,分别用于存储对话历史和当前显示的内容:

private Stack<string> _history = new Stack<string>();
private string _currentDialogue; // 记录当前正在显示的对话内容

2. 修改StartDialogue方法

启动新对话时,清空历史栈和当前对话记录,避免旧数据干扰:

public void StartDialogue(Dialogue dialogue)
{
    Debug.Log("Display information about " + dialogue.buildingName);

    animator.SetBool("IsOpen", true);

    buildingNameText.text = dialogue.buildingName;

    informations.Clear();
    _history.Clear(); // 清空对话历史
    _currentDialogue = null; // 重置当前对话

    foreach (string information in dialogue.informations)
    {
        informations.Enqueue(information);
    }

    DisplayNext();
}

3. 调整DisplayNext方法

切换到下一段对话时,将当前显示的内容存入历史栈,并记录新的当前对话:

public void DisplayNext()
{
    Debug.Log("Display next1");
    if (informations.Count == 0)
    {
        // 若还有当前对话,先存入历史再结束
        if (!string.IsNullOrEmpty(_currentDialogue))
        {
            _history.Push(_currentDialogue);
            _currentDialogue = null;
        }
        EndDialogue();
        return;
    }
    Debug.Log("Display next2");

    // 将当前显示的对话存入历史栈
    if (!string.IsNullOrEmpty(_currentDialogue))
    {
        _history.Push(_currentDialogue);
    }

    string information = informations.Dequeue();
    _currentDialogue = information; // 记录新的当前对话

    StopAllCoroutines();
    Debug.Log(information);
    StartCoroutine(TypeSentence(information));
}

4. 实现DisplayBack方法

回退时,将当前对话放回队列头部,再从历史栈取出上一段对话显示:

public void DisplayBack()
{
    Debug.Log("Display back");
    // 历史栈为空时,没有可回退的内容,直接返回
    if (_history.Count == 0)
    {
        return;
    }
    Debug.Log("Display back1");

    StopAllCoroutines();

    // 将当前对话放回队列最前面(Queue不支持直接插入头部,用临时列表中转)
    if (!string.IsNullOrEmpty(_currentDialogue))
    {
        List<string> tempQueueItems = informations.ToList();
        informations.Clear();
        informations.Enqueue(_currentDialogue);
        foreach (var item in tempQueueItems)
        {
            informations.Enqueue(item);
        }
        _currentDialogue = null;
    }

    // 取出历史栈中最近的一段对话并显示
    string lastDialogue = _history.Pop();
    _currentDialogue = lastDialogue;
    StartCoroutine(TypeSentence(lastDialogue));
}

逻辑说明

  • 每次切换到下一段对话,当前显示的内容会被存入历史栈(栈是后进先出,刚好匹配回退顺序)。
  • 回退时,先把当前未读完的对话放回队列头部,确保后续还能继续正常切换,再从历史栈取出上一段对话显示。
  • 完全保留了原有的Queue结构和原有逻辑,仅通过新增变量实现回退功能。

内容的提问来源于stack exchange,提问作者admin3333

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 05:30:59