import { _decorator, Component, Label, tween, UIOpacity } from 'cc'; const { ccclass, property } = _decorator; @ccclass('Toast') export class Toast extends Component { @property(Label) contentLabel: Label | null = null; private _uiOpacity: UIOpacity | null = null; onLoad() { // 获取或添加 UIOpacity 组件用于透明度动画 this._uiOpacity = this.node.getComponent(UIOpacity); if (!this._uiOpacity) { this._uiOpacity = this.node.addComponent(UIOpacity); } } /** * 显示 Toast * @param content 提示内容 * @param duration 显示时长(毫秒),默认 2000ms */ show(content: string, duration: number = 2000): void { if (this.contentLabel) { this.contentLabel.string = content; } // 重置透明度 this._uiOpacity!.opacity = 255; // 延迟后执行渐隐动画 this.scheduleOnce(() => { this._fadeOut(); }, duration / 1000); } /** * 渐隐动画并销毁 */ private _fadeOut(): void { tween(this._uiOpacity!) .to(0.3, { opacity: 0 }) .call(() => { this.node.destroy(); }) .start(); } }