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

My for i,v in pairs loop wont work and I don't know why?

for i, v in pairs(game.Workspace:GetChildren()) do 
	if v:IsA("Model") then 
		hum=v.Humanoid
		if hum==true then 
			v.Humanoid:Remove() 
		end 
	end 
end

1 answer

✓ Accepted answer

First of all, if you plan to ask lots of questions in ScriptingHelpers, it's best if you get used to wrap your code in between two sets of tilde symbols with this button, so that the code will be viewed like this:

for i, v in pairs(game.Workspace:GetChildren()) do if v:IsA("Model") then hum=v.Humanoid if hum==true then v.Humanoid:Remove() end end end

Second of all, reformat your code & utilize those whitespaces! They will make your code look more professional.

for i, v in pairs(game.Workspace:GetChildren()) do
	if v:IsA("Model") then
		hum=v.Humanoid
		if hum==true then
			v.Humanoid:Remove()
		end
	end
end

Look into the :FindFirstChild() method. It returns the child of its object given a string, or nil. An error is thrown due to models that do not have a Humanoid.

hum = v:FindFirstChild("Humanoid")
if hum then -- You absolutely do not need "== true", because "if" statements look at conditions that are true.

You've already defined Humanoid as hum. Why would you type more just to address it when you have a shorter alternative?

for i, v in pairs(workspace:GetChildren()) do
	if v:IsA("Model") then
		hum = v:FindFirstChild("Humanoid")
		if hum then
			hum:Destroy()
		end
	end
end

There's a more efficient way of doing this. Instead of looping through the WHOLE Workspace, why not loop through the players? That way you can use the Character property.

for i, Player in pairs(game.Players:GetPlayers()) do
	if Player.Character then
		hum = Player.Character:WaitForChild("Humanoid") -- Wait until `Humanoid` is not nil.
		if hum then
			hum:Destroy()
		end
	end
end

If the intended effect isn't achieved in this script, then try this instead (if you want to kill the characters).

for i, Player in pairs(game.Players:GetPlayers()) do
	if Player.Character then
		hum = Player.Character:WaitForChild("Humanoid")
		if hum then
			hum.Health = 0
		end
	end
end

But I don't know what you're trying to do, so don't use it if it doesn't apply to you. :P

Questions? Comments? Skepticism? Comment down below or PM!

1 comment

0

omg ty (praise)

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