Performance Issues With Mass-running Scripts

Hey there!
I am making a game, where you must collect bricks to buy upgrades to get even more bricks.
Now, my problem: Each player is expected to have around 240 Parts (Bricks) lying on a field that respawn at extremely rapid rates. Now, the problem is the collection of these bricks.

The spawning of the parts doesn’t create much of any lag due to a bunch of optimizations that I have already done.

As for the collection, the microprofiler SCREAMS that the scripts are hellish for the game’s overall performance.

A player can have up to 10 builders who collect bricks, around 7 bulldozers that collect bricks as well and their own character, that also collects bricks. Each and every single one of these has a serverscript in their hitbox that triggers the collection.

I believe that collecting these parts through about 20 scripts individually isnt the best approach.
Does anyone have a suggestion as to how to collect the parts in a resource-friendly way?

Thanks in advance.

Also, I don’t really think this is a scripting problem in terms of lua, so I didn’t provide any code. For anyone who is curious either way:

-- Script parented to the builder model. --
local player: Player = script.Parent:WaitForChild("Player").Value
local char: Model = script.Parent
local BrickCollection = require(game:GetService("ServerScriptService"):FindFirstChild("BrickCollection"))
local hitbox: Part = char:WaitForChild("HumanoidRootPart"):WaitForChild("ExtendedHitbox")
local ws = game:GetService("Workspace")

while hitbox do task.wait()
	
	for _, v in pairs(ws:GetPartsInPart(hitbox)) do
	
		-- Hold it right there! --
		
		local on = v.Name
		
		if on == "BrickA" or on == "BrickB" or on == "BrickC" or on == "BrickD" then
		
		-- --
		
			local brick = v
			
			if brick:FindFirstChild("Player") ~= nil then

				if brick:FindFirstChild("Player").Value == player then

					BrickCollection.collect(hitbox, player, brick)
				

				end

			end
			
		end

	end

end

First thing that comes to mind is going with an event based approach rather than having 20 scripts constantly running a while loop.
To this I would use 1 script that uses a container with all the collectable bricks.
This can either be tags or if you store all the bricks in one place like a folder you can use that.
Then loop through all the bricks and connect a .Touched event to them with the logic you have in the loop at the moment.
If you spawn another part you can either use a listener to detect if a part with that tag is added, the childAdded property or use the script you spawn the bricks with and add the connection as you spawn it.

With this approach you will only have 1 script that runs and gives connections to all the parts. The script will only executes once the touched event is fired rather than constantly running checking for changes.

Hope this helps!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.