87 lines
2.6 KiB
C#
87 lines
2.6 KiB
C#
|
|
using UnityEngine;
|
||
|
|
using UnityEngine.UI;
|
||
|
|
using TMPro;
|
||
|
|
using System.Collections.Generic;
|
||
|
|
using LLM;
|
||
|
|
|
||
|
|
namespace UI
|
||
|
|
{
|
||
|
|
public class ChatHistoryPanelController : MonoBehaviour
|
||
|
|
{
|
||
|
|
[Header("UI References")]
|
||
|
|
public Transform historyContent; // 历史记录的父物体 (ScrollView Content)
|
||
|
|
public GameObject messagePrefab; // 聊天气泡预设体,可复用 AssistPanel 的
|
||
|
|
|
||
|
|
[Header("Manager")]
|
||
|
|
public LLMChatManager chatManager; // 引用 LLMChatManager
|
||
|
|
|
||
|
|
private void OnEnable()
|
||
|
|
{
|
||
|
|
if (chatManager == null)
|
||
|
|
{
|
||
|
|
chatManager = FindObjectOfType<LLMChatManager>();
|
||
|
|
}
|
||
|
|
|
||
|
|
if (chatManager != null)
|
||
|
|
{
|
||
|
|
RefreshHistoryUI();
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
Debug.LogWarning("[ChatHistoryPanelController] LLMChatManager is missing!");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public void RefreshHistoryUI()
|
||
|
|
{
|
||
|
|
if (historyContent == null || messagePrefab == null) return;
|
||
|
|
|
||
|
|
// 清理旧的记录
|
||
|
|
foreach (Transform child in historyContent)
|
||
|
|
{
|
||
|
|
Destroy(child.gameObject);
|
||
|
|
}
|
||
|
|
|
||
|
|
// 获取全部历史记录
|
||
|
|
List<Message> fullLog = chatManager.fullChatLog;
|
||
|
|
if (fullLog == null || fullLog.Count == 0) return;
|
||
|
|
|
||
|
|
// 遍历并生成气泡
|
||
|
|
foreach (var msg in fullLog)
|
||
|
|
{
|
||
|
|
// 过滤掉 system 提示词等,只显示玩家和 AI 的对话
|
||
|
|
if (msg.role == "user" || msg.role == "assistant")
|
||
|
|
{
|
||
|
|
bool isPlayer = (msg.role == "user");
|
||
|
|
AddMessageToUI(msg.content, isPlayer);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 强制更新 Canvas 以确保布局正确,然后滚动到底部
|
||
|
|
Canvas.ForceUpdateCanvases();
|
||
|
|
ScrollRect scrollRect = historyContent.GetComponentInParent<ScrollRect>();
|
||
|
|
if (scrollRect != null)
|
||
|
|
{
|
||
|
|
scrollRect.verticalNormalizedPosition = 0f;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private void AddMessageToUI(string text, bool isPlayer)
|
||
|
|
{
|
||
|
|
GameObject newMsg = Instantiate(messagePrefab, historyContent);
|
||
|
|
TextMeshProUGUI tmp = newMsg.GetComponentInChildren<TextMeshProUGUI>();
|
||
|
|
|
||
|
|
if (tmp != null)
|
||
|
|
{
|
||
|
|
tmp.text = text;
|
||
|
|
}
|
||
|
|
|
||
|
|
var aligner = newMsg.GetComponent<MessageAligner>();
|
||
|
|
if (aligner != null)
|
||
|
|
{
|
||
|
|
aligner.SetAlignment(isPlayer);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|