Entity Manager Module

Hi all. Here is a small module for keeping track of existing entities of various types. Defold has no built-in way to check if an object exists, so this is my way of knowing if any players are alive, if the enemy I just killed was the last one, when the player is killed, etc.

Grab it here: entity_manager.lua (5.1 KB) or on Github.

It’s pretty simple, and I commented the heck out of the file, so hopefully it’s easy to figure out. You decide what entity groups you want and put those in the module, then there are four basic functions: Subscribe, Unsubscribe, Spawn, and Destroy, and the module sends out “entity spawned” and “entity destroyed” messages to the subscribers of each group.

For full documentation, go to the Github page.

It’s been through a few iterations and I’m using it in multiple projects now, so hopefully it can save other people some time. If you find some issues with it or think of feature requests, let me know!

:defold:

13 Likes

I just finished updating this to a slightly better design, added a few error checks, and added a getRandomEnt function thanks to @solariyoung. If you are using the older version you code should be totally compatible with the new version. I also wrote some proper documentation for everything on the Github page.

I tested it with spawning and destroying 1000 objects every frame and everything else I could think of to try to break it, and it worked fine. It’s still possible to use it incorrectly and cause bugs, but you should get some kind of message for most errors of usage. Of course if you find issues with it, let me know!

4 Likes