Files
Max-Cocos-Demo/assets/scripts/DontDestroy.ts
2025-10-28 21:55:41 +08:00

74 lines
1.9 KiB
TypeScript

/* eslint-disable no-console */
import { _decorator, Component, director } from "cc";
const { ccclass, property } = _decorator;
/**
* DontDestroy 组件
* 挂载此脚本的节点在场景切换时不会被自动销毁
*
* 使用场景:
* - 全局 UI 组件(如 Toast、Loading 等)
* - 音效管理器
* - 网络管理器
* - 其他需要跨场景保持的组件
*/
@ccclass("DontDestroy")
export class DontDestroy extends Component {
/**
* 标识是否已经设置为常驻节点
* 防止重复设置
*/
private _isPersistent: boolean = false;
protected onLoad(): void {
this.makePersistent();
}
/**
* 设置节点为常驻节点
*/
private makePersistent(): void {
if (this._isPersistent) {
console.warn(
`DontDestroy: 节点 ${this.node.name} 已经是常驻节点,无需重复设置`,
);
return;
}
// 设置节点为常驻节点,场景切换时不会被销毁
director.addPersistRootNode(this.node);
this._isPersistent = true;
console.log(`DontDestroy: 节点 ${this.node.name} 已设置为常驻节点`);
}
/**
* 手动移除常驻状态
* 调用此方法后,节点会在下次场景切换时被销毁
*/
public removePersistent(): void {
if (!this._isPersistent) {
console.warn(
`DontDestroy: 节点 ${this.node.name} 不是常驻节点,无需移除`,
);
return;
}
// 从常驻节点列表中移除
director.removePersistRootNode(this.node);
this._isPersistent = false;
console.log(
`DontDestroy: 节点 ${this.node.name} 已从常驻节点列表中移除`,
);
}
/**
* 检查节点是否为常驻节点
*/
public isPersistent(): boolean {
return this._isPersistent;
}
}