I'm trying to understand how Phaser.GameObjects.Container works. Here is the code.
class BootScene extends Phaser.Scene {
constructor() {
super();
}
create() {
this.menus = this.add.container();
var menuItemBlue = new Phaser.GameObjects.Text(this, 10, 30, 'Blue');
this.menus.add(menuItemBlue);
console.log(this.menus.length);
this.menus = this.add.container();
var menuItemRed = new Phaser.GameObjects.Text(this, 10, 50, 'Red');
this.menus.add(menuItemRed);
console.log(this.menus.length);
}
}
var config = {
width: 320,
height: 260,
scene: [BootScene]
}
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>
create() method adds two items to the container though, the length is always 1.
I also tried this
this.menus.add([menuItemBlue, menuItemRed]);
console.log(this.menus.length);
which outputs as expected, that is 2.
It seems that if I add items one by one, only the last one is kept by the container. If I want to keep them all, I have to put all the items in an array and then add the array to the container. Is my understanding correct?
Why does Phaser.GameObjects.Container work this way? Is there some consideration under the hood?
The problem is, that you are creating two containers this.menus = this.add.container();.
Remove the second "creation", and it works.
(I took your example and commented the second creating out, and now it works as expected)
just in case:
this.add.container()creates a container, and adds it to thescene.
class BootScene extends Phaser.Scene {
constructor() {
super();
}
create() {
// First Container
this.menus = this.add.container();
var menuItemBlue = new Phaser.GameObjects.Text(this, 10, 30, 'Blue');
this.menus.add(menuItemBlue);
console.log(this.menus.length);
// Second not needed Container
// this.menus = this.add.container();
var menuItemRed = new Phaser.GameObjects.Text(this, 10, 50, 'Red');
this.menus.add(menuItemRed);
console.log(this.menus.length);
}
}
var config = {
width: 320,
height: 260,
scene: [BootScene]
}
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>