Hi everyone!
I’m trying to create a script in PlayCanvas that loads assets dynamically before switching between scenes. The script works fine for the first scene (Start
) but fails to load assets for the next scene (Space
). My main issue is that the script is tied to an entity in the Start
scene, so it doesn’t persist when switching to another scene.
Currently, the script only loads assets tagged with Start
but ignores those tagged with Space
. I need the script to remain active across all scenes, dynamically load assets for the current scene, and handle scene transitions.
Here’s the script code:
// Create the preload script
var Preload = pc.createScript('preload');
// Initialize method
Preload.prototype.initialize = function () {
console.log("[Preload] Script initialized...");
// Load assets for the current scene (Start)
this.loadAssets('Start', () => {
console.log("[Preload] Start scene assets loaded successfully.");
// Then load assets for the next scene (Space)
this.loadAssets('Space', () => {
console.log("[Preload] Space scene assets loaded successfully.");
this.switchToScene('Space');
});
});
};
// Method to load assets by tag
Preload.prototype.loadAssets = function (tag, callback) {
const assets = this.app.assets.findByTag(tag);
console.log(`[Preload] Found ${assets.length} assets with tag: ${tag}`);
if (assets.length === 0) {
console.warn(`[Preload] No assets found with tag: ${tag}`);
if (callback) callback();
return;
}
let loadedCount = 0;
assets.forEach((asset) => {
console.log(`[Preload] Loading asset: ${asset.name} (${asset.type})`);
asset.once('load', () => {
console.log(`[Preload] Asset loaded: ${asset.name} (${asset.type})`);
loadedCount++;
// Callback when all assets are loaded
if (loadedCount === assets.length) {
console.log(`[Preload] All assets with tag '${tag}' loaded.`);
if (callback) callback();
}
});
this.app.assets.load(asset);
});
};
// Method to switch to another scene
Preload.prototype.switchToScene = function (sceneName) {
console.log(`[Preload] Switching to scene: ${sceneName}`);
const scene = this.app.scenes.find(sceneName);
if (scene) {
this.app.scenes.loadScene(scene.url, (err, loadedScene) => {
if (err) {
console.error(`[Preload] Failed to load scene: ${sceneName}`, err);
} else {
console.log(`[Preload] Scene '${sceneName}' successfully loaded.`);
}
});
} else {
console.error(`[Preload] Scene '${sceneName}' not found.`);
}
};
- How can I make the script global so it remains active across all scenes and handles asset loading dynamically?
- Why does the script only load assets for the first scene and not the subsequent scenes? How can I fix this behavior?
Any help would be greatly appreciated. Thanks in advance!