代码整理,ai相关配置转luban,聊天气泡缓存

This commit is contained in:
2025-08-13 11:31:21 +08:00
parent b511412833
commit db0b040fd8
78 changed files with 913 additions and 5189 deletions
@@ -1,7 +1,7 @@
import { _decorator, Component, instantiate, Node, Vec3 } from "cc";
import { DialogManager } from "../../manager/DialogManager";
import { DialogBubble } from "./DialogBubble";
import { Dialog } from "../../utils/DemoData";
import { Dialog } from "../../data/DialogData";
const { ccclass, property } = _decorator;
const BUTTOM_Y = -955.571;
@@ -16,6 +16,7 @@ export class ChatContentsLayout extends Component {
rBubble: DialogBubble = null;
bubbles: DialogBubble[] = [];
cachedBubbles: DialogBubble[] = [];
protected start(): void {
this.lBubble.node.active = false;
@@ -29,25 +30,45 @@ export class ChatContentsLayout extends Component {
}
UpdateDialog(dialogs: Dialog[]) {
//if (!this.bubbles) this.bubbles = [];
for (let i = this.bubbles.length - 1; i >= 0; i--) {
// 隐藏当前使用的气泡并放入缓存
for (let i = 0; i < this.bubbles.length; i++) {
if (this.bubbles[i].node) {
this.bubbles[i].node.destroy();
this.bubbles[i].node.active = false;
this.cachedBubbles.push(this.bubbles[i]);
}
}
this.bubbles = [];
let initPosY: number = BUTTOM_Y;
for (let i = dialogs.length - 1; i >= 0; i--) {
const dialog = dialogs[i]; //倒序
let newBubble: DialogBubble = null;
let newBubbleNode = dialog.isPlayer
? instantiate(this.rBubble.node)
: instantiate(this.lBubble.node);
let newBubble = newBubbleNode.getComponent(DialogBubble);
// 尝试从缓存中获取合适的气泡
const isPlayerBubble = dialog.isPlayer;
for (let j = 0; j < this.cachedBubbles.length; j++) {
const cached = this.cachedBubbles[j];
if (cached && cached.node) {
// 检查气泡类型是否匹配(通过位置判断左右气泡)
const isRightBubble = cached.node.position.x > 0;
if ((isPlayerBubble && isRightBubble) || (!isPlayerBubble && !isRightBubble)) {
newBubble = cached;
this.cachedBubbles.splice(j, 1);
break;
}
}
}
// 如果缓存中没有合适的气泡,创建新的
if (!newBubble) {
let newBubbleNode = isPlayerBubble
? instantiate(this.rBubble.node)
: instantiate(this.lBubble.node);
newBubble = newBubbleNode.getComponent(DialogBubble);
newBubbleNode.setParent(this.node);
}
newBubbleNode.setParent(this.node);
newBubble.node.active = true;
let offset = newBubble.updateBubbleContent(dialog.content);
let pos = newBubble.node.position;
@@ -56,5 +77,21 @@ export class ChatContentsLayout extends Component {
initPosY += offset + 20;
this.bubbles.push(newBubble);
}
// 清理多余的缓存气泡,避免内存泄漏
this.cleanupExcessCachedBubbles();
}
private cleanupExcessCachedBubbles() {
const maxCachedBubbles = 20; // 最大缓存数量
if (this.cachedBubbles.length > maxCachedBubbles) {
const excessCount = this.cachedBubbles.length - maxCachedBubbles;
for (let i = 0; i < excessCount; i++) {
const bubble = this.cachedBubbles.shift();
if (bubble && bubble.node) {
bubble.node.destroy();
}
}
}
}
}