Container doesn't render children when declared by 'new' keyword

I am trying to declare Container with new keyword for code modularization (referencing this article). However, when I declare one with new Container(), it doesn’t render its child image/sprite. What am I doing wrong here? Please see my code below:

var config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  backgroundColor: '#010101',
  parent: 'phaser-example',
  physics: {
    default: 'arcade',
    arcade: {
      gravity: { y: 200 },
      debug: true
    }
  },
  scene: {
    preload: preload,
    create: create
  }
};

var container1, container2;
var game = new Phaser.Game(config);

function preload () {
   this.load.image('mushroom', 'assets/sprites/mushroom2.png');
   this.load.image('lemming', 'assets/sprites/lemming.png');
}

function create () {
  var image1 = this.add.image(-40, 0, 'mushroom');
  var image2 = this.add.image(40, 0, 'lemming');

  container1 = this.add.container(100, 200);
  container1.add(image1);
  container1.setSize(128, 64);
  this.physics.world.enable(container1);
  container1.body.setVelocity(0, 200).setBounce(1, 1).setCollideWorldBounds(true);

  container2 = new Phaser.GameObjects.Container(this, 300, 200)
  container2.add(image2);
  container2.setSize(128, 64);
  this.physics.world.enable(container2);
  container2.body.setVelocity(0, 200).setBounce(1, 1).setCollideWorldBounds(true);

  // container1 renders image1, but container2 doesn't render image2.

  console.log(this.add.image, Phaser.GameObjects.Container);
  console.log(container1, container2);
  console.log(container1.list[0], container2.list[0]);
}

If you want to run this code, please go to Phaser3 SandBox, and copy & paste above code (sorry, I don’t know how to save my code there). Any help would be highly appreciated!

A new game object won’t be added to display list, or updating list, call this method to add this container to display list.

this.add.existing(container2);
2 Likes

Wow, it works like a charm after replacing
container2 = new Phaser.GameObjects.Container(this, 300, 200)
with
container2 = this.add.existing(new Phaser.GameObjects.Container(this, 300, 200))

Thank you so much!!

You may as well use :slight_smile:

container2 = this.add.container(300, 200);
1 Like