Factory Pattern in Godot


There are several ways to instantiate new objects with small variations. This project showcases some ways with different upsides and downsides.

The following article is a short overview over the samples contained in the project. For details check out the project files and watch this video by Ivan Skodje on youtube where he talks you through this showcase project.


1. SetupCode

The first example contained in the folder "SetupCode" simply preloads all textures for the different asteroids and the asteroid scene that defines the common basis of all asteroids. Then when _ready() is called the asteroid scene is instantiated and a function called "setup()" is called on the new instance, which takes a texture as a parameter and applies it to the asteroid.
If the asteroids should differ in more aspects than just the texture the setup function would be responsible for accepting the different values and applying them to the asteroid instance.

2. SetupCodeWithExport

The second example contained in the folder "SetupCodeWithExport" is quite similar to the first one, the only difference is that both the textures and the asteroid scene are exported, giving non-coders the option to exchange them for other textures resp. other scenes.

3. SpriteAnimation

The third example contained in the folder "SpriteAnimation" uses an AnimatedSprite instead of the Sprite to make exchanging the texture easier. The AnimatedSprite has a property called "Frames" that has a custom editor that allows you to pick any number of texture files and assign them to a frame number.


When instantiating an asteroid you now only have to set a random frame index to apply one of the textures at random.

4. Factory

The last example contained in the folder "Factory" works a little different from the previous ones. In this method I created a separate scene that contains any number of different asteroids. These asteroids can differ in any way you want, not just in the texture.


The script attached to this scene has a generate_asteroid()-function that takes an index as a parameter and returns a duplicate of the child node at that index in the factory scene.


Creating an instance is now about as easy as in the previous example, since again you only need to provide a random index to select a type of asteroid. The main difference is that now the new asteroid object is not created by calling instance() on a packed scene but by calling generate_asteroid() on an instance of the factory scene.