Hello everyone,
I made a script for my TDS game and I want to make sure it works with as much NPCs as possible
Module:
function ZombieHandler.SpawnZombie(Type)
local Zombie = {}
table.insert(ZombieHandler.ZombieList,Zombie)
Zombie.Type = Type
Zombie.Speed = ZombieStats.List[Type].Speed
Zombie.Health = ZombieStats.List[Type].Health
Zombie.Height = ZombieStats.List[Type].Height
Zombie.Part = Cache:GetPart()
Zombie.Position = 0
Zombie.Row = math.random(0,8)
Zombie.Part.Position = (workspace.Grass:FindFirstChild("SpawnZ"..Zombie.Row).Position - Vector3.new(0,workspace.Grass:FindFirstChild("SpawnZ"..Zombie.Row).Position.Y,0) ) + Vector3.new(0, GrassFolder:FindFirstChild("X0Z0").Position.Y + ZombieStats.List[Type].Height,0)
Zombie.Part.Parent = workspace.Zombies
setmetatable(Zombie,ZombieHandler)
Zombie.ZombieMovementEvent = Zombie.Part:GetAttributeChangedSignal("Active"):Connect(function()
Zombie:Move()
end)
return Zombie
end
function ZombieHandler:Move()
self.Position += 1
local Destination
local End
if GrassFolder:FindFirstChild("X"..self.Position.."Z"..self.Row) then
Destination = GrassFolder:FindFirstChild("X"..self.Position.."Z"..self.Row).Position + Vector3.new(0,self.Height,0)
else
Destination = self.Part.Position + Vector3.new(3,0,0)
End = true
end
local Distance = (Destination - self.Part.Position).Magnitude
local Tween = TweenService:Create(self.Part,TweenInfo.new(Distance / self.Speed,Enum.EasingStyle.Linear),{Position = Destination})
Tween:Play()
Tween.Completed:Once(function()
if End then
self:Kill()
end
self.Part:SetAttribute("Active",not self.Part:GetAttribute("Active"))
end)
end
function ZombieHandler:Kill()
self.Part.Color = Color3.fromRGB(163, 162, 165)
self.ZombieMovementEvent:Disconnect()
Cache:ReturnPart(self.Part)
table.remove(ZombieHandler.ZombieList,table.find(ZombieHandler.ZombieList,self))
print(#ZombieHandler.ZombieList)
end
a simple script that uses the said module:
for i = 1 , ZombieAmount do
local Zombie = ZombieModule.SpawnZombie(Zombies[math.random(1,3)])
Zombie.Part:SetAttribute("Active",true)
print("The workspace has a total of "..#workspace.Zombies:GetChildren())
task.wait()
end
it has around 1% activity and a rate of 60/s with 200 zombies if all the zombies are inside the field and are alive.
Is this code good enough and is there a way to optimize it further to accept more NPCs?
Thank you.