Spawning specific sprites

First of all please forgive me, as I only even heard of Defold yesterday. I have worked my way through the tutorials. I am a seasoned python programmer.

I am creating a simple GUI interface that will create a specific sprite depending on the key that is press. The key pressing delivers the correct key pressed, but I cannot work out how to spawn a specific sprite.

I have all the sprites loaded into a factory based on a prototype. I can spawn using the factory, but when the user presses a key, ALL the sprites spawned by the factory are generated and I cannot work out how to spawn just the sprite that I want to appear.

The code I am using is:

local component = “/createNumbers#numbersFactory”
factory.create(component, p)

This works, but displays ALL the sprites in the prototype.

Say I wanted to load a sprite in the game object prototype with an ID of 1. Is there any way of doing this?

local component = “/createNumbers#numbersFactory#1”
factory.create(component, p)

produces an error.

I don’t want to have to set up a prototype and factory for every single sprite, and I assume there is a better way of doing this?

The answer is probably really obvious, but as I said I only started with defold yesterday, so apologies again …

  • You should make a distinction between game object and sprite.
  • As opposed to some other engines, sprites in Defold are not objects, they are just components of an object.
  • If you want to spawn different things, for a example first a character, then a building, and then a car: then these should probably be different game objects, not the same game object with changing sprites.
    • The reason being that these objects will behave completely differently, they will have different colliders, different scripts, and so on.
    • For different game objects then you precisely need different factories, one for each.
  • If you want to spawn the same thing with changing appearance, for example first a Mercedes, then a BMW, and then a Tesla: then you have two options
    1. Create one atlas for each appearance you need, then at runtime you can swap the atlas of your sprite.
    2. Inside the same atlas, create a different animation for each appearance, and set it during runtime with sprite.play_flipbook().
  • If you definitely need to have one game object prefab, that has different sprites active every time it is spawned, then you need to disable the sprites you don’t need by sending them a disable message.

And lastly: welcome!


Thank you so much :slight_smile:

I like the idea of disabling sprites. I’ll give it a go and see how I get on :slight_smile:

Remember that with factories you can also pass properties so that when they are created you can react to that.

1 Like