Alternatives to iterating GO components

Hello everyone,

I’m a first time Defold user and I’m doing a learning project. To keep it simple, let’s say that I have a few levels and I’m loading them one at a time into a collection proxy. Each level should present the user with a variable number of images, which I want to appear sequentially, with a simple animation. To avoid code duplication, I’m using the same script for all levels, but the complication is that I need somehow to know how many images there are in each level.

I read that one cannot get all components of a game object, so my current approach is to define a mapping between the level number and the number of images it contains into a configuration file. This config is then imported into the levels script where I access the sprites by ID in a loop composing a prefix with the current index, up to the total number of images. This works but it’s not ideal because if I change the level and add/remove images I need to update the config, otherwise the script will fail.

I was wandering if I’m using the correct approach here, all the images are in sprites under a single game object. It seemed a little too verbose to create a game object for each single image, especially that the user is not expected to interact with them, they only serve as decor in the background. On the other hand, the game object has the exists() function, so I could get rid of the “number of images” configuration and just loop until the first non-existent game object. But are there any performance issues in doing that?

Are there any alternatives you can think of? How would you do it?

You could use one game object, sprite and script per image and have that script send a message to a level controller. The level controller receives the messages and adds each image to a list.

1 Like

Thanks, @britzl, for your suggestion. I tried it and it works. The object tree It’s a bit more complex with a game object for each sprite, but at least I can reuse the script that sends the message. Clever idea, I guess I have to re-frame my thinking to make use of these messages more. Paradigm shift, without a clutch :).

2 Likes