How do I make a proper Optimized Entity System?

I’m currently making a tower defense game, and when i spawn in multiple enemies (100~ enemies) it lags the game, so i’m trying to achieve a more optimized spawning system, i currently have a simple system that uses pivotto and updating pos+ori values every frame.


i have this currently, i spawned over 500~ enemies

this is over 200~ enemies and counting

and i notice my recv is over 3 digits and the cpu ms being higher than usual, i want a finished product like this (https://media.discordapp.net/attachments/664903629546717218/933694377270845510/aw2_2.gif)

I am using attributes and values to update the enemy position and orientation every frame.
CLIENTSIDED SCRIPT

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local EnemyModels = ReplicatedStorage.Enemy
local EnemyAnims = ReplicatedStorage.Anims

local enemies = {}
local Enemies = workspace.Enemies

local onRenderStepped = function(dt)
	for index, enemy in ipairs(enemies) do
		if not enemy then
			table.remove(enemies,index)
			continue
		end
		
		local Value = enemy.Parent
		local Position = Value:GetAttribute("EnemyPosition")
		local Orientation = Value:GetAttribute("EnemyOrientation")
		
		local PrimaryPart = enemy.PrimaryPart
		PrimaryPart:PivotTo(CFrame.lookAt(Position, Orientation))
	end	
end

local function ChildAdded(child)
	local Name = child.Name
	local Model = EnemyModels[Name]:Clone()
	Model.Parent = child
	
	local Humanoid = Model.Humanoid
	Humanoid:LoadAnimation(EnemyAnims[Name]):Play()
	
	table.insert(enemies,Model)
end

RunService.RenderStepped:Connect(onRenderStepped)
Enemies.ChildAdded:Connect(ChildAdded)

SERVERSIDED SCRIPT

local runservice = game:GetService("RunService")
local rs = game:GetService("ReplicatedStorage")

local Vector3new = Vector3.new
local module = {}
local enemies = {}
runservice.Heartbeat:Connect(function() -- trying to make a heartbeat function that takes not much performance.
	for i,v in ipairs(enemies) do
		local speed = v:GetAttribute("Speed")
		local PW = v:GetAttribute("Pathway")
		local MovingTo = v:GetAttribute("MovingTo") -- these variables can be replaced with a table but instead im going for a created value within the enemymodels folder.

		local map = workspace.map
		local Pathway = map["Pathways"..PW]
		
		if MovingTo > map:GetAttribute("MaxMovingTo") then
			v:Destroy()
			table.remove(enemies,i)
			continue
		end
		
		if Pathway[MovingTo] then
			local lastNode = nil
			local currNode = Pathway[MovingTo]
			if MovingTo - 1 == 0 then
				lastNode = map["Start"..PW]
			else
				lastNode = Pathway[MovingTo - 1]
			end

			if currNode == nil then
				if v ~= nil then
					v:Destroy()
				end

				table.remove(enemies,i)
				continue
			end

			local timecalc = tick() - v:GetAttribute("tick")
			local magn = (currNode.Position - lastNode.Position).Magnitude
			local dt = timecalc * speed/magn

			v:SetAttribute("EnemyPosition", lastNode.Position:Lerp(currNode.Position, dt))
			v:SetAttribute("EnemyOrientation", currNode.Position)
			
			if dt >= 1 then
				v:SetAttribute("MovingTo", MovingTo + 1)
				v:SetAttribute("tick", tick())
			end
		else
			v:Destroy()
			table.remove(enemies,i)
		end
	end
end)

function module.CreateEnemy(Amount,Enemy)
	for i = 1,Amount do
		local Value = script[Enemy]:Clone()
		Value.Parent = workspace.Enemies
		Value:SetAttribute("tick", tick())
		Value:SetAttribute("Pathways",1)
		Value:SetAttribute("MovingTo",1)

		table.insert(enemies,Value)
		
		task.wait(0.25)		
	end
end

return module

please give me anything / any info that could increase performance greatly. I’d love seeing my recv be below 10 kb/s despite there being 600 enemies actively moving.

3 Likes

Workspace:BulkMoveTo(EntityList, CFrameList) might help you.

1 Like

how would I be able to use this? It needs both an instance table and a cframe table which would need me to change my entire code because i am individually moving each enemy using the ancestor of each model.

1 Like

The network usage is probably from the fact that you’re updating the attribute every frame, which then has to replicate to the client. I would probably just use the attributes to store the positions and replicate their positions every couple frames using a remote event.

Btw, this isn’t really necessary, as it’s a microoptimisation.

Edit:
Almost forgot, here’s a really good resource on optimising stuff like this, it’s not about tower defense games, but I think a lot of the lessons can be applied here.

1 Like

interesting, i took a look at it a few minutes earlier and gave me a headache, i’ll check later.

1 Like

came back, i re-read this and this is what caught my eye, how could i do this? i dont know how to manually replicate stuff to the client,

1 Like

Just send the position and orientation through remote events every .10 seconds or so, and have the client use the positions and orientations it receives to update its models.

1 Like

update to this, i have fully converted to using tables, i have 2 separate tables, one for enemy data (for damaging) and one for enemy position.

I went and compared my old version to my new version (tables only) by creating 600 enemies
Because i used tables and only sent the most important information (position, orientation) it decreased network usage from 300kb/s to 100~ kb/s, no instance being made, only passing position and orientation values to the client.

I also created over 1600 enemies, and the results were amazing.
network usage went from 600-1100kb/s to a stable 250~ kb/s.
BEFORE


AFTER

although theres a change, i’m far from a legit optimized entity system. what more can i do to optimize my entity system?

I also switched to BulkMoveTo, it greatly increased performance


5 Likes

if you haven’t already, you can set the material of the parts in the npcs to smoothplastic for a very tiny fps boost
not as good as modifying the scripts for the npcs but if you really want to have 1800 spawned at once, it is useful

i would like to keep no change in part’s properties, altho thx for the tip

You can also use Vector3int16s to send 16bit numbers instead of 64bit lowering your recv data even more.

Then just simply send the enemies data every 20 heartbeats to all clients

With this you should get around 25kb of recv data with 350 enemies.

The only disadvantage with this is that you can’t use decimals in position and the range is a bit low. But you should still try use it for less recv data.

already finished with this project, i kept the humanoids because i wanted for accessories and clothing to still be used, it performscwell at 10kb/s at around 5k enemies, got too lazy so i never really used it, much of a hassle to import every single thing

If you want a smoother experience with humanoids you should also try disable all the unnecessary states from humanoid to prevent lag.

Also how can you get 10kb of recv data with 5000 enemies. I’ve tried many ways to make my recv data even lower. I think the lowest recv data with 5000 enemies is around 200kb of recv data which is pretty good for 5k enemies.

i use numbers for my entity system, and I only send data necessary (not too much data) and i let client run its “own” movement system which most of the time is accurate

Are you sending data every 20 heartbeats to all clients?

I send data when it is necessary, not constantly.

So you could send data only if enemy has spawned not just sending every heartbeat?