loading-assets
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLoading Assets
加载资源
The Phaser Loader () handles fetching all external content: images, audio, JSON, tilemaps, atlases, fonts, scripts, and more. Assets are queued inthis.load, loaded in parallel, and placed into global caches accessible by every Scene.preload()
Key source paths: , , ,
Related skills: ../game-setup-and-config/SKILL.md, ../scenes/SKILL.md, ../sprites-and-images/SKILL.md
src/loader/LoaderPlugin.jssrc/loader/File.jssrc/loader/filetypes/src/loader/events/Phaser Loader()负责获取所有外部内容:图片、音频、JSON、瓦片地图、图集、字体、脚本等。资源在this.load中排队,并行加载,然后放入全局缓存,供所有Scene访问。preload()
核心源码路径: 、、、
相关技能: ../game-setup-and-config/SKILL.md、../scenes/SKILL.md、../sprites-and-images/SKILL.md
src/loader/LoaderPlugin.jssrc/loader/File.jssrc/loader/filetypes/src/loader/events/Quick Start
快速入门
js
class GameScene extends Phaser.Scene {
preload() {
this.load.image('logo', 'assets/logo.png');
}
create() {
this.add.image(400, 300, 'logo');
}
}Assets loaded in are guaranteed to be ready when runs. The Loader starts automatically during the preload phase.
preload()create()js
class GameScene extends Phaser.Scene {
preload() {
this.load.image('logo', 'assets/logo.png');
}
create() {
this.add.image(400, 300, 'logo');
}
}在中加载的资源,会确保在执行时已准备就绪。Loader会在preload阶段自动启动。
preload()create()Core Concepts
核心概念
The Preload Pattern
Preload模式
Every Scene can define a method. The Loader automatically starts when completes and waits for all queued files to finish before calling .
preload()preload()create()js
preload() {
// Queue files - they don't load immediately
this.load.image('sky', 'assets/sky.png');
this.load.spritesheet('dude', 'assets/dude.png', { frameWidth: 32, frameHeight: 48 });
this.load.audio('jump', 'assets/jump.mp3');
}
create() {
// All assets above are now available
this.add.image(400, 300, 'sky');
this.add.sprite(100, 450, 'dude');
this.sound.play('jump');
}每个Scene都可以定义方法。当执行完成后,Loader会自动启动,并等待所有排队的文件加载完成后才调用。
preload()preload()create()js
preload() {
// 将文件加入队列——不会立即加载
this.load.image('sky', 'assets/sky.png');
this.load.spritesheet('dude', 'assets/dude.png', { frameWidth: 32, frameHeight: 48 });
this.load.audio('jump', 'assets/jump.mp3');
}
create() {
// 上述所有资源现在都已可用
this.add.image(400, 300, 'sky');
this.add.sprite(100, 450, 'dude');
this.sound.play('jump');
}Loading Outside of Preload
在Preload之外加载资源
If you call methods outside of (for example, in or in response to a user action), you must manually start the Loader:
this.loadpreload()create()js
create() {
this.load.image('extra', 'assets/extra.png');
this.load.once('complete', () => {
this.add.image(400, 300, 'extra');
});
this.load.start();
}如果在之外调用方法(例如在中或响应用户操作时),必须手动启动Loader:
preload()this.loadcreate()js
create() {
this.load.image('extra', 'assets/extra.png');
this.load.once('complete', () => {
this.add.image(400, 300, 'extra');
});
this.load.start();
}URL Resolution: baseURL, path, and prefix
URL解析:baseURL、path和prefix
The final URL for a file is resolved as: . These can be set via the game config or at runtime.
baseURL + path + filenamejs
preload() {
// Set base URL (prepended to all relative paths)
this.load.setBaseURL('https://cdn.example.com/');
// Set path (prepended after baseURL, before filename)
this.load.setPath('assets/images/');
// Set key prefix (prepended to the cache key, not the URL)
this.load.setPrefix('LEVEL1.');
// Loads from: https://cdn.example.com/assets/images/hero.png
// Cached with key: LEVEL1.hero
this.load.image('hero', 'hero.png');
// Absolute URLs bypass the path/baseURL
this.load.image('cloud', 'https://other-server.com/cloud.png');
}These can also be set in the game config:
js
const config = {
loader: {
baseURL: 'https://cdn.example.com/',
path: 'assets/',
prefix: '',
maxParallelDownloads: 32,
crossOrigin: 'anonymous',
responseType: '',
async: true,
timeout: 0,
maxRetries: 2,
imageLoadType: 'XHR' // or 'HTMLImageElement'
}
};文件的最终URL解析规则为:。这些参数可通过游戏配置或运行时设置。
baseURL + path + filenamejs
preload() {
// 设置基础URL(会添加到所有相对路径前)
this.load.setBaseURL('https://cdn.example.com/');
// 设置路径(添加在baseURL之后、文件名之前)
this.load.setPath('assets/images/');
// 设置缓存键前缀(添加到缓存键前,不会影响URL)
this.load.setPrefix('LEVEL1.');
// 加载路径为:https://cdn.example.com/assets/images/hero.png
// 缓存键为:LEVEL1.hero
this.load.image('hero', 'hero.png');
// 绝对URL会绕过path和baseURL设置
this.load.image('cloud', 'https://other-server.com/cloud.png');
}这些参数也可以在游戏配置中设置:
js
const config = {
loader: {
baseURL: 'https://cdn.example.com/',
path: 'assets/',
prefix: '',
maxParallelDownloads: 32,
crossOrigin: 'anonymous',
responseType: '',
async: true,
timeout: 0,
maxRetries: 2,
imageLoadType: 'XHR' // 或 'HTMLImageElement'
}
};Global Caches
全局缓存
Assets are stored in global game-level caches, not per-Scene. An image loaded in one Scene is available in every other Scene. Textures go into (the Texture Manager). Other data goes into sub-caches (e.g., , , ).
game.texturesgame.cachegame.cache.jsongame.cache.audiogame.cache.xml资源存储在游戏级别的全局缓存中,而非Scene级缓存。在一个Scene中加载的图片,可在所有其他Scene中使用。纹理会存入(纹理管理器),其他数据则存入的子缓存(例如、、)。
game.texturesgame.cachegame.cache.jsongame.cache.audiogame.cache.xmlLoad Events
加载事件
The Loader emits events throughout the loading lifecycle. Use these for progress bars and loading screens.
js
preload() {
this.load.on('progress', (value) => {
// value is 0 to 1
console.log(`Loading: ${Math.round(value * 100)}%`);
});
this.load.on('complete', () => {
console.log('All assets loaded');
});
this.load.on('loaderror', (file) => {
console.warn('Failed to load:', file.key);
});
this.load.image('bg', 'assets/bg.png');
}Loader会在加载生命周期中触发各类事件,可用于实现进度条和加载界面。
js
preload() {
this.load.on('progress', (value) => {
// value取值范围为0到1
console.log(`加载进度:${Math.round(value * 100)}%`);
});
this.load.on('complete', () => {
console.log('所有资源加载完成');
});
this.load.on('loaderror', (file) => {
console.warn('加载失败:', file.key);
});
this.load.image('bg', 'assets/bg.png');
}Common Patterns
常见用法
Loading Images and Sprite Sheets
加载图片和精灵表
js
preload() {
// Single image
this.load.image('star', 'assets/star.png');
// Image with normal map (pass URL array: [texture, normalMap])
this.load.image('brick', ['assets/brick.png', 'assets/brick_n.png']);
// Sprite sheet (fixed frame sizes)
this.load.spritesheet('explosion', 'assets/explosion.png', {
frameWidth: 64,
frameHeight: 64,
startFrame: 0,
endFrame: 23,
margin: 0,
spacing: 0
});
// SVG (optionally rasterize at a specific size)
this.load.svg('logo', 'assets/logo.svg', { width: 400, height: 400 });
}js
preload() {
// 单张图片
this.load.image('star', 'assets/star.png');
// 带法线贴图的图片(传入URL数组:[纹理, 法线贴图])
this.load.image('brick', ['assets/brick.png', 'assets/brick_n.png']);
// 精灵表(固定帧尺寸)
this.load.spritesheet('explosion', 'assets/explosion.png', {
frameWidth: 64,
frameHeight: 64,
startFrame: 0,
endFrame: 23,
margin: 0,
spacing: 0
});
// SVG图片(可选择按指定尺寸光栅化)
this.load.svg('logo', 'assets/logo.svg', { width: 400, height: 400 });
}Loading Audio
加载音频
js
preload() {
// Single file
this.load.audio('bgm', 'assets/music.mp3');
// Multiple formats for cross-browser support
this.load.audio('bgm', ['assets/music.ogg', 'assets/music.mp3']);
// Audio sprite (JSON defines named regions within a single audio file)
this.load.audioSprite('sfx', 'assets/sfx.json', [
'assets/sfx.ogg',
'assets/sfx.mp3'
]);
}js
preload() {
// 单个音频文件
this.load.audio('bgm', 'assets/music.mp3');
// 多格式文件以支持跨浏览器
this.load.audio('bgm', ['assets/music.ogg', 'assets/music.mp3']);
// 音频精灵(JSON定义单个音频文件中的命名片段)
this.load.audioSprite('sfx', 'assets/sfx.json', [
'assets/sfx.ogg',
'assets/sfx.mp3'
]);
}Loading JSON and Tilemaps
加载JSON和瓦片地图
js
preload() {
// JSON data (stored in this.cache.json)
this.load.json('levelData', 'assets/level1.json');
// JSON with a dataKey to extract a sub-object
this.load.json('enemies', 'assets/data.json', 'enemies');
// Tiled tilemap (JSON format exported from Tiled)
this.load.tilemapTiledJSON('map', 'assets/map.json');
// CSV tilemap
this.load.tilemapCSV('csvmap', 'assets/level.csv');
// Impact tilemap
this.load.tilemapImpact('impactmap', 'assets/level.js');
}
create() {
const data = this.cache.json.get('levelData');
const map = this.make.tilemap({ key: 'map' });
}js
preload() {
// JSON数据(存储在this.cache.json中)
this.load.json('levelData', 'assets/level1.json');
// 提取子对象的JSON(通过dataKey指定)
this.load.json('enemies', 'assets/data.json', 'enemies');
// Tiled瓦片地图(从Tiled导出的JSON格式)
this.load.tilemapTiledJSON('map', 'assets/map.json');
// CSV格式瓦片地图
this.load.tilemapCSV('csvmap', 'assets/level.csv');
// Impact格式瓦片地图
this.load.tilemapImpact('impactmap', 'assets/level.js');
}
create() {
const data = this.cache.json.get('levelData');
const map = this.make.tilemap({ key: 'map' });
}Loading Atlases
加载图集
js
preload() {
// JSON atlas (e.g., TexturePacker JSON Hash/Array)
this.load.atlas('sprites', 'assets/sprites.png', 'assets/sprites.json');
// XML atlas (e.g., Starling/Sparrow format)
this.load.atlasXML('ui', 'assets/ui.png', 'assets/ui.xml');
// Multi-atlas (atlas split across multiple textures)
this.load.multiatlas('world', 'assets/world.json', 'assets/');
// Unity texture atlas format
this.load.unityAtlas('chars', 'assets/chars.png', 'assets/chars.txt');
// Aseprite atlas
this.load.aseprite('knight', 'assets/knight.png', 'assets/knight.json');
}
create() {
this.add.sprite(400, 300, 'sprites', 'walk_01');
}js
preload() {
// JSON图集(例如TexturePacker JSON Hash/Array格式)
this.load.atlas('sprites', 'assets/sprites.png', 'assets/sprites.json');
// XML图集(例如Starling/Sparrow格式)
this.load.atlasXML('ui', 'assets/ui.png', 'assets/ui.xml');
// 多图集(图集拆分到多个纹理文件)
this.load.multiatlas('world', 'assets/world.json', 'assets/');
// Unity纹理图集格式
this.load.unityAtlas('chars', 'assets/chars.png', 'assets/chars.txt');
// Aseprite图集
this.load.aseprite('knight', 'assets/knight.png', 'assets/knight.json');
}
create() {
this.add.sprite(400, 300, 'sprites', 'walk_01');
}Loading Bitmap Fonts
加载位图字体
js
preload() {
// Requires both a texture and XML/JSON font data file
this.load.bitmapFont('pixels', 'assets/font.png', 'assets/font.xml');
}
create() {
this.add.bitmapText(100, 100, 'pixels', 'Hello World', 32);
}js
preload() {
// 需要同时加载纹理和XML/JSON字体数据文件
this.load.bitmapFont('pixels', 'assets/font.png', 'assets/font.xml');
}
create() {
this.add.bitmapText(100, 100, 'pixels', 'Hello World', 32);
}Loading Video
加载视频
js
preload() {
// Load a video file. Third arg: noAudio flag (default false)
this.load.video('intro', 'assets/intro.mp4');
// Load without audio track
this.load.video('bg_loop', 'assets/loop.mp4', true);
}js
preload() {
// 加载视频文件。第三个参数:noAudio标志(默认false)
this.load.video('intro', 'assets/intro.mp4');
// 加载不含音轨的视频
this.load.video('bg_loop', 'assets/loop.mp4', true);
}Loading Web Fonts
加载Web字体
js
preload() {
// Load a font file (ttf, otf, woff, woff2)
this.load.font('myFont', 'assets/myfont.ttf', 'truetype');
// With optional font face descriptors
this.load.font('boldFont', 'assets/bold.woff2', 'woff2', {
weight: 'bold',
style: 'normal'
});
}js
preload() {
// 加载字体文件(ttf、otf、woff、woff2格式)
this.load.font('myFont', 'assets/myfont.ttf', 'truetype');
// 带可选字体描述符
this.load.font('boldFont', 'assets/bold.woff2', 'woff2', {
weight: 'bold',
style: 'normal'
});
}Loading a Pack File
加载打包文件
A pack file is a JSON file that describes multiple assets to load at once. Useful for organizing asset manifests.
js
preload() {
this.load.pack('pack1', 'assets/pack.json');
}Pack file format:
json
{
"section1": {
"baseURL": "assets/",
"files": [
{ "type": "image", "key": "bg", "url": "bg.png" },
{ "type": "atlas", "key": "chars", "textureURL": "chars.png", "atlasURL": "chars.json" }
]
}
}打包文件是一个JSON文件,用于描述需要一次性加载的多个资源,便于组织资源清单。
js
preload() {
this.load.pack('pack1', 'assets/pack.json');
}打包文件格式:
json
{
"section1": {
"baseURL": "assets/",
"files": [
{ "type": "image", "key": "bg", "url": "bg.png" },
{ "type": "atlas", "key": "chars", "textureURL": "chars.png", "atlasURL": "chars.json" }
]
}
}Loading with a Progress Bar
实现加载进度条
js
preload() {
const progressBar = this.add.graphics();
const progressBox = this.add.graphics();
progressBox.fillStyle(0x222222, 0.8);
progressBox.fillRect(240, 270, 320, 50);
this.load.on('progress', (value) => {
progressBar.clear();
progressBar.fillStyle(0xffffff, 1);
progressBar.fillRect(250, 280, 300 * value, 30);
});
this.load.on('complete', () => {
progressBar.destroy();
progressBox.destroy();
});
// Queue your assets
this.load.image('sky', 'assets/sky.png');
// ... more assets
}js
preload() {
const progressBar = this.add.graphics();
const progressBox = this.add.graphics();
progressBox.fillStyle(0x222222, 0.8);
progressBox.fillRect(240, 270, 320, 50);
this.load.on('progress', (value) => {
progressBar.clear();
progressBar.fillStyle(0xffffff, 1);
progressBar.fillRect(250, 280, 300 * value, 30);
});
this.load.on('complete', () => {
progressBar.destroy();
progressBox.destroy();
});
// 加入需要加载的资源
this.load.image('sky', 'assets/sky.png');
// ... 更多资源
}All File Types Reference
全文件类型参考
All methods accept positional arguments or a single config object. They also accept an array of config objects to batch-load multiple files of the same type. See for the complete parameter table.
this.loadreferences/REFERENCE.mdTextures: , , , , , , , , , (compressed)
Audio/Video: , ,
Data: , , , , , ,
Fonts: ,
Tilemaps: , ,
Other: , , , , , ,
imagespritesheetatlasatlasXMLmultiatlasunityAtlasasepritesvghtmlTexturetextureaudioaudioSpritevideojsonxmltextbinaryhtmlcssglslbitmapFontfonttilemapTiledJSONtilemapCSVtilemapImpactanimationpackscriptscriptspluginscenePluginsceneFile所有方法均接受位置参数或单个配置对象,也可接受配置对象数组以批量加载同类型的多个文件。完整参数表请参考。
this.loadreferences/REFERENCE.md纹理类: 、、、、、、、、、(压缩纹理)
音频/视频类: 、、
数据类: 、、、、、、
字体类: 、
瓦片地图类: 、、
其他: 、、、、、、
imagespritesheetatlasatlasXMLmultiatlasunityAtlasasepritesvghtmlTexturetextureaudioaudioSpritevideojsonxmltextbinaryhtmlcssglslbitmapFontfonttilemapTiledJSONtilemapCSVtilemapImpactanimationpackscriptscriptspluginscenePluginsceneFileEvents
事件
All events are emitted on the Loader instance ().
this.load| Event String | Callback Signature | Description |
|---|---|---|
| | A file was added to the load queue |
| | Loader has started. Progress is zero |
| | A single file finished loading (before processing/caching) |
| | Per-file download progress (0-1). Only fires if browser provides |
| | Overall load progress updated (0-1) |
| | All files loaded and processed, before internal cleanup |
| | Any file finished loading and processing |
| | Specific file finished (e.g., |
| | A file failed to load |
| | All files in the queue are done |
所有事件均在Loader实例()上触发。
this.load| 事件字符串 | 回调签名 | 描述 |
|---|---|---|
| | 文件被加入加载队列 |
| | Loader已启动,进度为0 |
| | 单个文件完成下载(在处理/缓存之前) |
| | 单个文件的下载进度(0-1),仅当浏览器提供 |
| | 整体加载进度更新(0-1) |
| | 所有文件加载并处理完成,内部清理之前 |
| | 任意文件完成加载和处理 |
| | 指定文件完成加载(例如 |
| | 文件加载失败 |
| | 队列中所有文件处理完成 |
Event Lifecycle Order
事件生命周期顺序
- - Loader begins
'start' - - Per-file progress (repeats per file, if available)
'fileprogress' - - Each file finishes downloading
'load' - - Specific file processed and cached
'filecomplete-{type}-{key}' - - Generic per-file completion
'filecomplete' - - Overall progress updated
'progress' - - All files done, before cleanup
'postprocess' - - Everything finished
'complete'
- - Loader开始
'start' - - 单个文件进度更新(若支持,会重复触发)
'fileprogress' - - 单个文件下载完成
'load' - - 指定文件处理并缓存完成
'filecomplete-{type}-{key}' - - 通用单个文件完成事件
'filecomplete' - - 整体进度更新
'progress' - - 所有文件处理完成,清理之前
'postprocess' - - 所有操作完成
'complete'
Gotchas and Common Mistakes
常见陷阱与错误
Keys must be unique within their type. Loading a second image with the same key as an existing one will log a warning and skip it. Remove the old texture from the Texture Manager first if you need to replace it.
Sprite sheet is not the same as an atlas. Use for fixed-size grids of frames (referenced by index). Use for packed texture atlases with named frames.
spritesheet()atlas()Forgetting outside preload. If you call load methods in or later, the Loader does not auto-start. You must call manually.
this.load.start()create()this.load.start()Path must end with . If you call it will append the slash automatically. If you set directly, you must include the trailing slash yourself.
/this.load.setPath()this.load.pathAudio format fallbacks. Always provide multiple audio formats (OGG + MP3 at minimum) for cross-browser support. The Loader picks the first format the browser supports.
Pack files can override baseURL/path/prefix. Each section in a pack file can set its own , , and values. These apply only to files within that section and are restored after the section is processed.
baseURLpathprefixFile keys include the prefix. If you set and load an image with key , the actual cache key becomes . You must use that full key when referencing the asset.
this.load.setPrefix('MENU.')'bg''MENU.bg'The property (default: 2) controls how many times the Loader retries a failed file before giving up. This is set per-file at creation time based on . Adjusting it after files are added has no effect on those files.
maxRetriesthis.load.maxRetriesImage load type. By default images load via XHR (as blobs). Set in the loader config to use tag loading instead, which can help with CORS issues in some environments.
imageLoadType: 'HTMLImageElement'<img>Local file schemes. The Loader recognizes and as local schemes by default (via ). Files loaded from local schemes skip CORS headers.
file://capacitor://localSchemesCross-origin. Set in the loader config (or via ) when loading assets from a different domain, especially if those textures will be used with WebGL.
crossOrigin: 'anonymous'this.load.setCORS('anonymous')Keys are case-sensitive and scoped per type. and are different keys. An image key and an audio key can coexist without conflict.
'Player''player''player''player'Duplicate keys are silently ignored. A second call does nothing if already exists in the texture cache. Remove the old asset first to replace it.
this.load.image('bg', ...)'bg'Scene does NOT fire during preload. While assets are loading, is paused. However, , , and still fire.
update()update()preupdatepostupdaterenderProgress can decrease. If new files are added mid-load (e.g., via chaining), the progress value may drop because the total file count increased.
filecomplete同类型资源的键必须唯一。若加载的第二个图片与现有图片键相同,会触发警告并跳过加载。如需替换,需先从纹理管理器中移除旧纹理。
精灵表和图集不同。用于固定尺寸的帧网格(通过索引引用),用于带命名帧的打包纹理图集。
spritesheet()atlas()在preload之外加载时忘记调用。如果在或之后调用加载方法,Loader不会自动启动,必须手动调用。
this.load.start()create()this.load.start()路径必须以结尾。使用会自动添加斜杠,但直接设置时,必须手动添加末尾斜杠。
/this.load.setPath()this.load.path音频格式需提供备选。为支持跨浏览器,至少提供OGG和MP3两种格式,Loader会选择浏览器支持的第一个格式。
打包文件会覆盖baseURL/path/prefix。打包文件中的每个章节都可设置自己的、和,这些设置仅对该章节内的文件生效,章节处理完成后会恢复原有设置。
baseURLpathprefix缓存键包含前缀。若设置并加载键为的图片,实际缓存键为,引用资源时必须使用完整键名。
this.load.setPrefix('MENU.')'bg''MENU.bg'**属性(默认值:2)**控制Loader在放弃前重试失败文件的次数,该值在文件创建时基于设置,添加文件后调整该值不会影响已加入队列的文件。
maxRetriesthis.load.maxRetries图片加载类型。默认图片通过XHR加载(以blob形式),在Loader配置中设置可改用标签加载,这在某些环境下可解决CORS问题。
imageLoadType: 'HTMLImageElement'<img>本地文件协议。Loader默认将和识别为本地协议(通过),从本地协议加载的文件会跳过CORS头。
file://capacitor://localSchemes跨域设置。从不同域名加载资源时,需在Loader配置中设置(或通过),尤其是当这些纹理将用于WebGL时。
crossOrigin: 'anonymous'this.load.setCORS('anonymous')键区分大小写且按类型作用域。和是不同的键,图片键和音频键可共存且互不冲突。
'Player''player''player''player'重复键会被静默忽略。若纹理缓存中已存在,第二次调用不会产生任何效果,如需替换需先移除旧资源。
'bg'this.load.image('bg', ...)Scene的在preload期间不会触发。资源加载时,会暂停,但、和仍会触发。
update()update()preupdatepostupdaterender进度值可能下降。若在加载过程中添加新文件(例如通过链式加载),进度值可能会下降,因为总文件数增加了。
filecompleteScene Payload (Load Before Preload)
Scene预加载包(Preload前加载)
Load files before runs by defining a in the Scene constructor. Useful for loading progress bar assets.
preload()packjs
class BootScene extends Phaser.Scene {
constructor() {
super({
key: 'BootScene',
pack: {
files: [
{ type: 'image', key: 'bar', url: 'loaderBar.png' }
]
}
});
}
// 'bar' is already available in preload()
}通过在Scene构造函数中定义,可在运行前加载文件,适用于加载进度条资源。
packpreload()js
class BootScene extends Phaser.Scene {
constructor() {
super({
key: 'BootScene',
pack: {
files: [
{ type: 'image', key: 'bar', url: 'loaderBar.png' }
]
}
});
}
// 'bar'在preload()中已可用
}Adding Files Mid-Load
加载过程中添加文件
Use the per-file completion event to chain dependent loads during an active loading session.
js
preload() {
this.load.json('level1', 'level1.json');
this.load.on('filecomplete-json-level1', (key, type, data) => {
this.load.image(data.images);
this.load.spritesheet(data.spritesheets);
});
}利用单个文件完成事件,可在加载会话中链式加载依赖资源。
js
preload() {
this.load.json('level1', 'level1.json');
this.load.on('filecomplete-json-level1', (key, type, data) => {
this.load.image(data.images);
this.load.spritesheet(data.spritesheets);
});
}Inline Pack Manifests
内联打包清单
Pack data can be provided inline instead of from a URL.
js
preload() {
this.load.pack('manifest', {
section1: {
prefix: '',
path: 'assets/',
defaultType: 'image',
files: [
{ type: 'image', key: 'bg', url: 'bg.png' },
{ type: 'spritesheet', key: 'player', url: 'player.png', frameConfig: { frameWidth: 32, frameHeight: 32 } }
]
}
});
}可直接提供内联的打包数据,而非从URL加载。
js
preload() {
this.load.pack('manifest', {
section1: {
prefix: '',
path: 'assets/',
defaultType: 'image',
files: [
{ type: 'image', key: 'bg', url: 'bg.png' },
{ type: 'spritesheet', key: 'player', url: 'player.png', frameConfig: { frameWidth: 32, frameHeight: 32 } }
]
}
});
}Cache System
缓存系统
Loaded assets go into global caches shared across all Scenes. Textures are stored in the Texture Manager (); other asset types go into typed sub-caches under .
this.texturesthis.cachejs
// Access cached data
const json = this.cache.json.get('levelData');
const text = this.cache.text.get('dialogue');
// Check existence
this.cache.json.exists('levelData'); // or .has('levelData')
this.textures.exists('hero');
// Remove assets to free memory
this.textures.remove('hero');
this.cache.audio.remove('bgm');
// Listen for cross-scene texture additions
this.textures.on('addtexture-mapKey', (texture) => {
// Another scene loaded 'mapKey' — now available here
});Cache sub-types: , , , , , . See for the full Cache API.
this.cache.textthis.cache.jsonthis.cache.audiothis.cache.binarythis.cache.shaderthis.cache.xmlreferences/REFERENCE.md加载的资源会存入所有Scene共享的全局缓存。纹理存储在纹理管理器()中,其他类型的资源存入下的子缓存。
this.texturesthis.cachejs
// 访问缓存数据
const json = this.cache.json.get('levelData');
const text = this.cache.text.get('dialogue');
// 检查资源是否存在
this.cache.json.exists('levelData'); // 或使用.has('levelData')
this.textures.exists('hero');
// 移除资源释放内存
this.textures.remove('hero');
this.cache.audio.remove('bgm');
// 监听跨Scene的纹理添加事件
this.textures.on('addtexture-mapKey', (texture) => {
// 其他Scene加载了'mapKey'——现在可在此处使用
});缓存子类型:、、、、、。完整缓存API请参考。
this.cache.textthis.cache.jsonthis.cache.audiothis.cache.binarythis.cache.shaderthis.cache.xmlreferences/REFERENCE.mdSource File Map
源码文件映射
See for the complete source file map and Cache API reference.
references/REFERENCE.mdKey files: (main Loader), (base File class), (all file type loaders), (event constants).
src/loader/LoaderPlugin.jssrc/loader/File.jssrc/loader/filetypes/src/loader/events/完整源码文件映射和缓存API参考请见。
references/REFERENCE.md核心文件:(主Loader)、(基础文件类)、(所有文件类型加载器)、(事件常量)。
src/loader/LoaderPlugin.jssrc/loader/File.jssrc/loader/filetypes/src/loader/events/