Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

GetPartBoundsInBox firing multiple times?

I'm making a basic script to give 100 money every second a player is in a certain area (like Jailbreak) for practice but I've always been running into an error where it fires even though the player has left the area. It'll fire for a certain time depending on how long the player was in the area so I think it's just an issue with updating the table but I can't fix it.

while true do
	local db = false
	local parts = workspace:GetPartBoundsInBox(script.Parent.CFrame,script.Parent.Size,nil)
	if db == false then
		db = true
	for i,part in (parts) do
		if part.Parent:FindFirstChild("Humanoid") then
			local plr = game.Players:GetPlayerFromCharacter(part.Parent)
				plr.leaderstats.Money.Value = plr.leaderstats.Money.Value + 100
				wait(1)
				db = false
				plr = nil
			end
		end
	end
end

Removing debounce fixes it but I can't really do that for an actual game.

1 answer

✓ Accepted answer
for i,part in (parts) do
        if part.Parent:FindFirstChild("Humanoid") then
            local plr = game.Players:GetPlayerFromCharacter(part.Parent)
                plr.leaderstats.Money.Value = plr.leaderstats.Money.Value + 100
                wait(1)
                db = false
                plr = nil
            end
        end
    end

You're giving them money for every single part in parts that is parented to a character.

A better way to do this would be:

char = nil
for i, part in (parts) do
	if part.Parent:FindFirstChild("Humanoid") then
		char = part.Parent
		break
	end
end
if char then
	local plr = game.Players:GetPlayerFromCharacter(part.Parent)
	plr.leaderstats.Money.Value += 100
	wait(1)
	db = false
	plr = nil
end

In this example, the script will only give money once to a single char because it stops looping after it finds a character.

Make sure to put a wait somewhere so that the script doesn't crash if a char isn't found

This discussion is preserved as it was. New answers, comments, and votes are closed.