Help Creating Modular Weapon System

I think the code you have is the wrong way to go if you want a wide variety using composition. I made a similar composition system for enemies in my game.

To set up composition the first thing you need is a “World” that will keep track of entities (IDs for weapons) and keep them into dense arrays for good performance. But dense arrays are optional

Then you can create weapon prefabs and assign components to them. For example the pistol prefab will have a Bullet component, a Reload component, and maybe a Knockback component. However, the wand prefab would have a MagicMissile component and a ManaUsage component. These components purely store data, and if you have constant data that doesn’t have to be dynamic then you can store a reference to some kind of config table inside the component

--example component

-- holds static data if you want to save some memory
local pistolConfig = {
  totalBullets = 10,
  damage = 30,
}

-- only dynamic data that has to change, which is why we create new table each time
local function createBulletComponent()
  return {
    config = pistolConfig 
    currentBullets = 10
    reloadTimer = 0
  }
end

Now the world should store components in a table, and you can use systems to loop through components and implement the functionality. For example, when the user clicks, it fires an event that some systems like BulletSystem or MagicMissileSystem will pick up on and do their respective thing

1 Like