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

How to fix "for n,k in pairs(game.Players:GetChildren())" breaking when someone dies?

I have a script that I got from a free model. I've been working with it for a while now to add a lot more uses to it, but it seems that the original code, and therefore this code, breaks whenever someone dies. This script in particular uses multiple things I'm unfamiliar with, so I have genuinely no clue how to fix this.

while true do
	for n,k in pairs(game.Players:GetChildren()) do
		if (script.Parent.Position - k.Character.Torso.Position).magnitude < distance then
			check = check + 1
		end
	end
	if check >= 1 then
		if open == false then
			open = true
			for i = 0,width*2 do

				//(stuff)

				wait(0.05)
			end
		end
		else if check == 0 then
			if open == true then
				open = false
				for i = 0,width*2 do
					
				//(more stuff)

				end
			end
		end
	end
	check = 0 
	wait()
end

3 comments

0

check if k is nil

0

check if k is nil

0

@Goulstem: surely k will never be nil? If it was, it wouldn't be returned by 'pairs'

1 answer

✓ Accepted answer

The problem is that k.Character.Torso might not exist, and trying to access it without using FindFirstChild causes an error that will stop the script from running further. I'm unsure if k.Character is guaranteed to exist either, so it won't hurt to check that as well. To check these, we can improve your 'if' statement in the 'for' loop (line 3):

if k.Character and k.Character:FindFirstChild("HumanoidRootPart") and (script.Parent.Position - k.Character.HumanoidRootPart.Position).magnitude < distance then

As you can see, we've added k.Character and k.Character:FindFirstChild("HumanoidRootPart") and. Note that we're replacing Torso with HumanoidRootPart because the newer character models don't have a Torso, they have an UpperTorso (but both have a HumanoidRootPart). If k.Character is nil, lua will stop evaluating the 'if' there because it's an 'and'. The same thing goes for the next part, k.Character:FindFirstChild("HumanoidRootPart"). If both of these values are non-nil, lua will continue looking through the 'if'. Note that this only works because we are joining all the expressions with and. If you're unsure how it works, simply use multiple if statements, like this:

if k.Character then
	if k.Character:FindFirstChild("HumanoidRootPart") then
		--your original if here (with Torso replaced with HumanoidRootPart)
	end
end

Either way, your script will no longer try to fetch a part that doesn't exist, and it therefore won't run into any errors when a player dies.

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