How would I be able to make this basic ECS entity handler script so it can handle spawning entities [NPC]'s and giving their respective behavior?

Heya Everyone!!
I’m working on a side project from my main project which is a YOMI Hustle-styled game as a way to practice using ECS since I’m new to it. I’ve made a basic ECS entity handler script that simply just spawns a basic enemy that doesn’t do anything right now.
The goal is that I want to turn it into a proper entity handler script where it can sort out the enemies it needs to spawn and give it functionality.

For some information, the current ECS script is a server script but I’m planning on making it into a module script. The issue is that I don’t really know how I would use a module script for ECS. Also, I’m using Jecs. The module is placed in ServerScriptService.

EDIT: I FORGOT TO MENTION THAT THE CODE IS INSPIRED BY A YOUTUBE TUTORIAL GOING OVER ECS WITH JECS

--[[SERVICES]]--
local ServerScriptService = game:GetService("ServerScriptService")
local ServerStorage = game:GetService("ServerStorage")

--[[ECS SYSTEM]]--
local jecs = require(ServerScriptService.SERVER_MODULE_SCRIPTS:WaitForChild("jecs"))

--[[SETTING UP JEC AND COMPONENTS]]--
local world = jecs.World.new()
local EntityNPC = world:component()
local Moveset = world:component() --//Will be used later

--[[ENTITY FUNCTIONALITY]]--

--//This is simply just spawning the entity indefinitely
local SpawnEntity do
	
	function SpawnEntity()
		local E = world:entity()
		local NPC = ServerStorage.ENTITY_FOLDER:WaitForChild("Noob"):Clone()
		NPC.Parent = game.Workspace
		
		world:set(E, EntityNPC, NPC)
	end
	
end

while task.wait(5) do
	SpawnEntity()
end

I’ve notice this isn’t gaining any attraction, so I might as well bump this.

you could try moving your SpawnEntity() function, im not too great at coding but i have an example

local jecs = require(game.ServerScriptService.SERVER_MODULE_SCRIPTS.jecs)
local world = jecs.World.new()

local EntityNPC = world:component()
local Moveset = world:component()

local EntityHandler = {}

function EntityHandler.SpawnEntity()
    local E = world:entity()
    local NPC = game.ServerStorage.ENTITY_FOLDER.Noob:Clone()
    NPC.Parent = workspace
    world:set(E, EntityNPC, NPC)
    world:set(E, Moveset, "Idle") -- or whadever tag you want (no it was not a misspell i prefer saying whadever insteada whatever)
end

return EntityHandler

dunno if thisll even work tho but its worth a try

didnt really explain what i meant but point is you wrap it in a module

While I’m not too familiar with jecs itself I am also trying to implement my own approach to ECS.

With the way I implemented mine, isn’t jecs capable of creating systems of some sort? And then passing the required components into a query function or something? I’m pretty sure it has a function similar to that or somewhere I’m not sure.

You could then have some entities (Enemies) with varying components such as an AttackComponent, DamageComponent or an AngerComponent that those systems run on using those queries.

For varying types of a specific component (again with the way I’m doing it and if possible using jecs) I would recommend using a config dependency approach as it removes the need for deep inheritance chains and you are able to separate it into a different module for easy modification.

So for your SpawnEntity() function that would obviously, well spawn an entity but also give the entity the components that you want it to have. You would then have systems (queries) that operate on those components somewhere outside the function that manages different tasks however I’m not sure on how you would exactly implement this.

Again I’m not too familiar with jecs so I could be completely wrong here but I hope this rambling I did was useful. :slightly_smiling_face::+1:

You need systems, a scheduler of your choice, jecs has a demo on their repo.
Oh also, you are likely to need to replicate the components. (if the logic is just movement, etc)

Your systems must query the specific components it relies on, and then simply do the desired behaviour on it.

Example:

local function System(dt: number)
    --// Query all Entities that have Velocity and Renderable Part set
    for EntityId: number, Velocity: number, Part: BasePart in world:query(components.Velocity, components.Renderable) do
        Part.Position += Velocity * dt
    end
end

return System --// The scheduler runs this in a heartbeat

I’ll be completely honest, I haven’t read both Jec’s Devforum and Github pages. I read Jec’s DevForum post and:

It does have systems. But as you said earlier, you aren’t really familiar with Jecs.

Okay then, so the systems is used to query specific components that is essential (Such as moving) and then add its desired behavior to it? Also, three questions as well:

  • How does the system exactly work? For example how does it query all the entities with specific sets?
  • What would you expect for something like that to appear in a fully completed module script? (I’m genuinely so sorry if I worded this wrong its like 1 O’ clock on my end and my brain is starting to get tired.)
  • If I do have to replicate the components for different entities, how would I do so?

They just apply logic to queried entites (if there are any) every Heartbeat, PreRender (your choice).

Components are really just ID’s you assign to an entity, and jecs just does fast ID lookup.
local HealthComponent = 17817
local Entity = 871871
world:set(Entity, HealthComponent, 100)

There are open source packages that handle jecs replication for you. You don’t have to worry about that

Basically I do it like this:
I have a Setup module in ReplicatedStorage for both Server and Client to require on start.
The setup module returns a Setup function that takes in array of ModuleScripts (The systems)
Then it requires the System, and inserts into systems array to execute.
Exmample what the system might returns:

return {
   Phase = "Heartbeat",
   System = System --// The system function to run on chosen phase "Heartbeat"
}

Then client and server calls the setup function and passes systems, server and client systems.
Example hierarchy:

ReplicatedStorage
     Systems
         Physics--// ModuleScript (server AND client system)
     Setup --// ModuleScript
ServerScriptService
     Systems
         HealthRegen --// Server-sided system
         PoisonDamage --// Server-sided system
     Init --// ServerScript that Setups systems -> Setup(ReplicatedStorage.Systems + ServerScriptService.Systems)
StarterPlayerScripts
     Systems
         Camera --// Client-sided system
     Init --// LocalScript that Setups systems -> Setup(script.Parent.Systems:GetChildren())

You get the idea

I don’t use JECS atm, I instead wrote a really simple DOD Manager, completely customized for my project.

Also, since JECS relies on Systems, you’d want to use a Collect function from their demo.
It essentially returns an iterator which returns any arguments from desired Event.
local PlayerAdded = Collect(Players.PlayerAdded)
for Player: Player in PlayerAdded do ← The body of this loop only runs when the iterator has anything to return from the Event.

Thank you. I’ll go through it and try to make something similar to the one you did later and give you some updates on it.