Hello Cocos Creator community,
I am developing a 2D game in Cocos Creator 3.8.6 where each level has a different configuration stored in a JSON file. The JSON looks like this:
{
"Levels": [
{ "id": 1, "bg": "BgLevel1", "pointToBeat": 20 },
{ "id": 2, "bg": "BgLevel2", "pointToBeat": 20 },
{ "id": 3, "bg": "BgLevel3", "pointToBeat": 20 },
{ "id": 4, "bg": "BgLevel4", "pointToBeat": 20 },
{ "id": 5, "bg": "BgLevel5", "pointToBeat": 20 }
// ... more levels
]
}
I load this JSON in a GameManager
singleton component, which parses and stores the level data. Then, in my SetLevel
component, I try to load the background image dynamically based on the bg
property of the current level.
Here is the relevant code snippet from SetLevel.ts
where I attempt to load the sprite:
const path = `Levels/${levelData.bg}`; // e.g. "Levels/BgLevel4"
resources.load(path, SpriteFrame, (err, spriteFrame) => {
if (err) {
console.error(`Error loading sprite at ${path}:`, err);
return;
}
this.backgroundSprite.spriteFrame = spriteFrame;
});
My images are .webp
files placed inside assets/resources/Levels/
. In the editor, when I click on these images, they show as type SpriteFrame, so I expect resources.load
to work with SpriteFrame
type.
However, I get the following error at runtime:
Error loading sprite at Levels/BgLevel4: Error: Bundle resources doesn’t contain Levels/BgLevel4
I have verified:
- The files are inside the
resources
folder. - The path is correct and matches the file names exactly (case-sensitive).
- The project is saved and rebuilt after adding the assets.
backgroundSprite
is properly assigned in the editor.
Thank you very much in advance!