How to implement common code and resources in different game objects?


My roguelike has a main hero character, enemies and npcs. Some of their behaviours are common, such has catching on fire when walking over a fire trap. At the moment, the code to handle this is duplicated in the script file for each character’s game object. Also the fire animation has to be added separately to each game object.

Is there a way of somehow having a common game object or another way of just having one set of code and resources for these common things?


Hello Ben,

Getting ahead of @britzl, have you tried a Lua script to share the code between your objects? :grin:

I don’t know your code but an idea would be something like (pseudocode):

on your scripts:

-- somewhere in the upper part of the script
local fire_trap = require('fire_trap')

-- later...
function on_message(...)

   if == contact_point
       if == FIRE_TRAP


Yes, I had thought of that approach - I could also simply add a common script file to the various game objects. Either of those would solve part of the problem but still leaving the issue of other shared resources being duplicated across the game objects.


:thinking: Hmmm…

Shared resources…

(by the way, I edited my previous answer to add an idea in pseudocode)


For the shared resources, have you tried using a factory in those objects?

a catch_fire_factory…


Thanks for the pseudocode :slight_smile:

Now using a factory to create a child game object sounds like it could work. I’ll do some experiments…

Thanks again for your input!


I’m not a big fan of having a ton of scripts per game object, but maybe you could have a catch_fire.script on the game objects and have"enabled", false) that decides if it is enabled or not? Or, as @Edgaronfo suggests, Lua modules with this behaviour and require that code from the npc, enemy and hero?