Creating objects without adding them to scene

In all the examples I have seen, adding a new object (sprite, etc.) is a matter of calling add.[object] on the scene, which immediately adds it to the scene.

What if I want to create objects but not add them to the scene (visibly)? I would like to write a function that creates a container with various objects in it, returns the container, and then allow the caller to add it to the scene.

Even using new Phaser.GameObjects.[object] requires a scene as the first argument.

Also, writing individual functions to create the objects would prevent me from having to pass a scene to that function, otherwise I have to pass references of the scene all over the place.

All game objects need to be given a scene. There’s no way to construct a Game Object without a scene (or at least no intentional way; because this is JavaScript, it might be possible to put together an unstable hack that avoids it).

That said, the constructors (Phaser.GameObjects.[object]) will not add the object to the scene by themselves. You can create any game object you want, then use scene.add.existing to add it to the scene.

Thanks @Telinc1.

I think what I really want, though, is a means to create an object independently so that I can create functions that will construct compound objects (like containers with children) without having to have access to the scene themselves.

Perhaps I just need to rethink the structure of my code in that case.

You’d need to rethink the structure. Game objects are dependent on a scene, even if they’re not part of its display list or update list.

1 Like