Does looping through over 500 objects cause lag?

So these monsters blow up structures made of blocks in my game. Now, I’m not sure if I should ray cast to damage the blocks, or loop through every single block checking its distance between the player. I choose to loop through every block checking it’s magnitude. But it especially does this when I have TNTs that do the same thing as the monsters do, and they have the same exact code. So normally around 40 TNTs spawn during this event, and that’s 40 loops with 500 objects. That causes a lot of performance issues. So if someone supplied me with a short system to fix this I’d implement it right away with no problem.

Note that there is no other things in the area of the script as I know of is affecting performance too. These monsters in my game have been around for over 3 months now, and I work on the game every day.

Thanks for any replies

So, something causes an explosion, and you want to know what is within its explosion radius? Instead of querying everything, consider using WorldRoot:GetPartBoundsInRadius (roblox.com)
This will return a table of everything within a radius you’d define with position of the explosion and radius you define as how many studs away you want something to be affected by an explosion.
You may want to carefully setup its overlapParams filtering to make sure it doesn’t like… unweld the baseplate.

1 Like

Well I’m actually not using an explosion, but if that’s the only option I’ll do it

WAIT HOLD ON I THOUGHT YOU WERE TALKING ABOUT EXPLOSIONS. Okay let me check this out

1 Like

Btw, what is a WorldRoot? And how do I use the GetPartsBoundsInRadius?

WorldRoot is game.Workspace
An example of how to use it:

local overlapParams = OverlapParams.new()
overlapParams.MaxParts = 10

local parts = game.Workspace:GetPartBoundsInRadius(workspace.Part.Position, 10, overlapParams)

for _, v in pairs(parts) do
    print(v:GetFullName())
end

This would return a table containing up to 10 parts that are within 10 studs of an instance Part in workspace. You can iterate it like with the loop to do something with each thing in the table.

2 Likes

Okay so how would I be able to make it where it gets all parts in its radius of 10 studs? Would I just put 100 max parts?

1 Like

I did MaxParts as an example of constructing an OverlapParams, don’t specify MaxParts at all and it will return everything, no limit.

1 Like

Omg thx so much I’m going to be using this method!

1 Like