import { _decorator, Component, Node, Sprite, SpriteFrame, resources } from 'cc'; const { ccclass, property } = _decorator; @ccclass('AvatarManager') export class AvatarManager extends Component { @property({ type: Sprite, tooltip: '头像显示的Sprite组件' }) avatarSprite: Sprite = null; @property({ tooltip: '头像资源的前缀,例如"avatar_"或者留空' }) avatarPrefix: string = ''; @property({ tooltip: '头像资源的后缀,默认为".png"' }) avatarSuffix: string = '.png'; // 当前显示的头像ID private currentAvatarId: number = 0; /** * 根据角色ID加载并显示对应的头像 * @param characterId 角色ID * @param callback 加载完成的回调函数 */ public loadAvatar(characterId: number, callback?: () => void): void { if (!this.avatarSprite) { console.error('头像Sprite组件未设置'); callback && callback(); return; } this.currentAvatarId = characterId; // 构建头像资源路径 const avatarPath = `avatars/${this.avatarPrefix}${characterId}${this.avatarSuffix}/spriteFrame`; // 加载头像资源 resources.load(avatarPath, SpriteFrame, (err, spriteFrame) => { if (err) { console.error(`加载头像失败: ${avatarPath}`, err); callback && callback(); return; } // 设置头像 this.avatarSprite.spriteFrame = spriteFrame; // 调用回调函数 callback && callback(); }); } /** * 获取当前显示的头像ID */ public getCurrentAvatarId(): number { return this.currentAvatarId; } /** * 清除当前显示的头像 */ public clearAvatar(): void { if (this.avatarSprite) { this.avatarSprite.spriteFrame = null; } this.currentAvatarId = 0; } }