AvatarManager.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { _decorator, Component, Node, Sprite, SpriteFrame, resources } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('AvatarManager')
  4. export class AvatarManager extends Component {
  5. @property({
  6. type: Sprite,
  7. tooltip: '头像显示的Sprite组件'
  8. })
  9. avatarSprite: Sprite = null;
  10. @property({
  11. tooltip: '头像资源的前缀,例如"avatar_"或者留空'
  12. })
  13. avatarPrefix: string = '';
  14. @property({
  15. tooltip: '头像资源的后缀,默认为".png"'
  16. })
  17. avatarSuffix: string = '.png';
  18. // 当前显示的头像ID
  19. private currentAvatarId: number = 0;
  20. /**
  21. * 根据角色ID加载并显示对应的头像
  22. * @param characterId 角色ID
  23. * @param callback 加载完成的回调函数
  24. */
  25. public loadAvatar(characterId: number, callback?: () => void): void {
  26. if (!this.avatarSprite) {
  27. console.error('头像Sprite组件未设置');
  28. callback && callback();
  29. return;
  30. }
  31. this.currentAvatarId = characterId;
  32. // 构建头像资源路径
  33. const avatarPath = `avatars/${this.avatarPrefix}${characterId}${this.avatarSuffix}/spriteFrame`;
  34. // 加载头像资源
  35. resources.load(avatarPath, SpriteFrame, (err, spriteFrame) => {
  36. if (err) {
  37. console.error(`加载头像失败: ${avatarPath}`, err);
  38. callback && callback();
  39. return;
  40. }
  41. // 设置头像
  42. this.avatarSprite.spriteFrame = spriteFrame;
  43. // 调用回调函数
  44. callback && callback();
  45. });
  46. }
  47. /**
  48. * 获取当前显示的头像ID
  49. */
  50. public getCurrentAvatarId(): number {
  51. return this.currentAvatarId;
  52. }
  53. /**
  54. * 清除当前显示的头像
  55. */
  56. public clearAvatar(): void {
  57. if (this.avatarSprite) {
  58. this.avatarSprite.spriteFrame = null;
  59. }
  60. this.currentAvatarId = 0;
  61. }
  62. }