Phaser3启动游戏传递参数失败,如何正确实现参数传递?
问题原因与解决方案
问题根源
- 场景Key不匹配:BootScene类定义时指定的key是
'Boot',但你在index.js中添加场景时使用的key是'BootScene',Phaser无法将传递的参数与正确的场景实例关联。 - 参数接收方式错误:Phaser的
init和create方法会将传递的参数作为单个对象传入,而非多个零散参数,使用...params会把数据对象包裹进空数组,导致你看到"空对象"的错误结果。
修复步骤
1. 统一场景Key
修改boot.js中的场景key,与index.js中添加场景时的key保持一致:
// boot.js import { Scene } from 'phaser' export default class BootScene extends Phaser.Scene { constructor() { super({ key: 'BootScene' }) // 改为与index.js一致的key } preload() { this.load.image('logo', './assets/logo.png') } // ... 其他方法 }
2. 修正参数接收逻辑
将init和create的参数改为直接接收单个数据对象:
// boot.js init(data){ console.info('INIT', data) // 此时会正确拿到{user:'test', auth:'test-auth'} } create(){ // 如需将参数传递给下一个场景,可在start时携带 this.scene.start('PreloadScene', {user: data.user, auth: data.auth}) }
3. 可选:简化场景配置方式
你也可以直接在phaserConfig的scene数组中配置场景并传递初始数据,无需手动调用game.scene.add:
// index.js phaserConfig.scene = [ { key: 'BootScene', class: BootScene, data: {user:'test', auth:'test-auth'} }, PreloadScene, GameScene ] // 移除后续的game.scene.add代码 // let game = new Phaser.Game(phaserConfig) // game.scene.add(...)
内容的提问来源于stack exchange,提问作者Diego
相关产品推荐
相关产品推荐

