ResourceExplorer.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { _decorator, Component, Node, Button, Label, ScrollView, resources, instantiate, Prefab } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('ResourceExplorer')
  4. export class ResourceExplorer extends Component {
  5. @property({
  6. type: Label,
  7. tooltip: '资源路径标签'
  8. })
  9. pathLabel: Label = null;
  10. @property({
  11. type: Button,
  12. tooltip: '扫描按钮'
  13. })
  14. scanButton: Button = null;
  15. @property({
  16. type: Label,
  17. tooltip: '结果标签'
  18. })
  19. resultLabel: Label = null;
  20. @property({
  21. tooltip: '要扫描的资源路径'
  22. })
  23. resourcePath: string = 'avatars';
  24. start() {
  25. // 注册扫描按钮点击事件
  26. if (this.scanButton) {
  27. this.scanButton.node.on(Button.EventType.CLICK, this.onScanButtonClick, this);
  28. }
  29. // 更新路径显示
  30. this.updatePathDisplay();
  31. }
  32. updatePathDisplay() {
  33. if (this.pathLabel) {
  34. this.pathLabel.string = `当前路径: ${this.resourcePath}`;
  35. }
  36. }
  37. onScanButtonClick() {
  38. this.scanResources();
  39. }
  40. scanResources() {
  41. this.showResult(`正在扫描路径: ${this.resourcePath}...`);
  42. resources.loadDir(this.resourcePath, (err, assets) => {
  43. if (err) {
  44. this.showResult(`扫描失败: ${err.message}`);
  45. return;
  46. }
  47. let result = `找到 ${assets.length} 个资源:\n\n`;
  48. if (assets.length === 0) {
  49. result += "没有找到资源,请确认路径是否正确。";
  50. } else {
  51. assets.forEach((asset, index) => {
  52. result += `${index + 1}. ${asset.name} (${asset.constructor ? asset.constructor.name : '未知类型'})\n`;
  53. });
  54. }
  55. this.showResult(result);
  56. });
  57. }
  58. showResult(message: string) {
  59. if (this.resultLabel) {
  60. this.resultLabel.string = message;
  61. }
  62. console.log(message);
  63. }
  64. setResourcePath(path: string) {
  65. this.resourcePath = path;
  66. this.updatePathDisplay();
  67. }
  68. navigateToParent() {
  69. const parts = this.resourcePath.split('/');
  70. if (parts.length > 1) {
  71. parts.pop();
  72. this.resourcePath = parts.join('/');
  73. } else {
  74. this.resourcePath = '';
  75. }
  76. this.updatePathDisplay();
  77. }
  78. navigateToChild(childName: string) {
  79. if (this.resourcePath) {
  80. this.resourcePath += '/' + childName;
  81. } else {
  82. this.resourcePath = childName;
  83. }
  84. this.updatePathDisplay();
  85. }
  86. onDestroy() {
  87. // 清理事件监听
  88. if (this.scanButton) {
  89. this.scanButton.node.off(Button.EventType.CLICK, this.onScanButtonClick, this);
  90. }
  91. }
  92. }