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

Unity中如何隔离聊天框内机器人Dave的文本以优化TTS?

解决Unity聊天机器人TTS过载问题:仅播放Dave的新回复

问题根源

现有代码中,OAICompletion的ResponseReceivedEvent1传递的是完整聊天历史,而SimpleCharacter的Talk方法错误地将全部聊天内容传给TTS,导致每次都重复播放所有对话,引发过载。

修复步骤

1. 修改OAICompletion,传递单独的回复内容

找到OAICompletion类中的AddResponseToMemory方法,将事件触发的参数从完整聊天历史改为当前新增的回复内容:

public void AddResponseToMemory (string value)
{
    memory.Append(value).Append(InjectRestartText);
    // 仅传递最新的单条回复,而非完整聊天记录
    ResponseReceivedEvent1?.Invoke(value);
    Debug.Log("Memory: " + memory);
}

2. 在SimpleCharacter中绑定事件并处理单条回复

首先在SimpleCharacter中添加OAICharacter的引用(需在Unity Inspector面板中赋值):

public OAICharacter _oaiCharacter; // 新增引用

然后修改Start方法,绑定事件以接收Dave的新回复:

void Start()
{
    Debug.Log("Simple Character start 0 ");
    anim = GetComponentInChildren<Animator>();
    if (anim == null)
    {
        Debug.Log(&quot;Simple Character anim is null&quot;);
    }
    // 绑定事件,监听Dave的新回复
    _oaiCharacter.ResponseReceivedEvent1.AddListener(OnDaveReplyReceived);
    Debug.Log(&quot;Simple Character start 1&quot;);
}

新增处理回复的方法,仅播放当前回复并更新聊天界面:

private void OnDaveReplyReceived(string daveReply)
{
    // 修复聊天界面文本覆盖问题,追加新回复
    string currentChat = chatText.text;
    if (!string.IsNullOrEmpty(currentChat))
    {
        currentChat += &quot;\n&quot;;
    }
    currentChat += $&quot;Dave: {daveReply}&quot;;
    chatText.text = currentChat;

    // 仅将当前回复传给TTS播放
    _speaker.Speak(daveReply);
    
    // 触发说话动画
    anim.SetTrigger(&quot;Talk&quot;);
}

3. 清理冗余代码

删除SimpleCharacter中不需要的Talk重载方法,避免逻辑混淆:

  • 移除public void Talk(List<Choice> choices)
  • 移除public void Talk(string text)

4. 统一聊天记录格式(可选)

若希望聊天界面格式更清晰,可修改OAICharacter的标识文本:

public override string InjectStartText { get => &quot;\nDave: &quot;; set => throw new System.NotImplementedException(); }
public override string InjectRestartText { get => &quot;\nHuman: &quot;; set => throw new System.NotImplementedException(); }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:41:07