Phaser 3 在场景之间共享自定义对象数据?
Phaser 3 share custom object data between scenes?
我的 GameScene 中有一个 class 自定义对象。
this.player = new Player(
this,
this.game.config.width * 0.5,
this.game.config.height * 0.5,
"playerShip"
);
这个对象有生命和得分。将所有玩家数据传递到另一个场景的最佳方式是什么?我试图将它存储到 localstorage 并获取不同场景中的数据,但它丢失了所有 class 属性。我不能将数据作为参数传递,因为每个场景之后都是 2 个对话场景,然后是新的播放场景
本地存储,以及任何游戏内存储,如游戏注册表或游戏缓存,都会序列化数据。在为这些存储机制序列化时,您将丢失这些 class 属性。
如果你想从持久存储中水化,你需要在每次从某种存储机制中持久化和水化序列化数据时构建一个新的class。
为了在序列化之间保留对这些 classes 的对象引用,或者作为状态水合作用的替代方法,您需要在全局某处存储引用。
您可以扩展 Phaser.Game class 以使事情更加类型安全,但似乎移相器游戏实例允许扩展以获得更快的解决方案。只需添加对 class 实例的引用,您就可以在任何场景中访问它。 Stackblitz Example
我喜欢使用的一种方法是 Phaser.Plugins.BasePlugin
。
class Player extends Phaser.Plugins.BasePlugin {
constructor(pluginManager) {
super(pluginManager);
//initialize player state
}
//Additional methods for getting managing player data
isAlive() { return true; }
}
//in your JS entry file
let config = {
type: Phaser.AUTO,
parent: 'game'
},
plugins: {
global: [ //make the Player global to all scenes (and other plugins)
// key is plugin key, plugin is class, start true/false if there
// is a start method to run, mapping is the name tagged of this
// to access the plugin class
{ key: 'Player', plugin: Player, start: false, mapping: 'player'}
]
}
};
//In the scene
class MyScene extends Phaser.Scene {
update(){
if(this.player.isAlive()) {
//do some stuff
}
}
}
我还为我的插件启用了存储状态到本地存储。这对于与游戏会话之间玩家库存进度的任务状态相关的插件很有用。
DataManager
class可用于场景间共享数据
看看this example。
我的 GameScene 中有一个 class 自定义对象。
this.player = new Player(
this,
this.game.config.width * 0.5,
this.game.config.height * 0.5,
"playerShip"
);
这个对象有生命和得分。将所有玩家数据传递到另一个场景的最佳方式是什么?我试图将它存储到 localstorage 并获取不同场景中的数据,但它丢失了所有 class 属性。我不能将数据作为参数传递,因为每个场景之后都是 2 个对话场景,然后是新的播放场景
本地存储,以及任何游戏内存储,如游戏注册表或游戏缓存,都会序列化数据。在为这些存储机制序列化时,您将丢失这些 class 属性。
如果你想从持久存储中水化,你需要在每次从某种存储机制中持久化和水化序列化数据时构建一个新的class。
为了在序列化之间保留对这些 classes 的对象引用,或者作为状态水合作用的替代方法,您需要在全局某处存储引用。
您可以扩展 Phaser.Game class 以使事情更加类型安全,但似乎移相器游戏实例允许扩展以获得更快的解决方案。只需添加对 class 实例的引用,您就可以在任何场景中访问它。 Stackblitz Example
我喜欢使用的一种方法是 Phaser.Plugins.BasePlugin
。
class Player extends Phaser.Plugins.BasePlugin {
constructor(pluginManager) {
super(pluginManager);
//initialize player state
}
//Additional methods for getting managing player data
isAlive() { return true; }
}
//in your JS entry file
let config = {
type: Phaser.AUTO,
parent: 'game'
},
plugins: {
global: [ //make the Player global to all scenes (and other plugins)
// key is plugin key, plugin is class, start true/false if there
// is a start method to run, mapping is the name tagged of this
// to access the plugin class
{ key: 'Player', plugin: Player, start: false, mapping: 'player'}
]
}
};
//In the scene
class MyScene extends Phaser.Scene {
update(){
if(this.player.isAlive()) {
//do some stuff
}
}
}
我还为我的插件启用了存储状态到本地存储。这对于与游戏会话之间玩家库存进度的任务状态相关的插件很有用。
DataManager
class可用于场景间共享数据
看看this example。