for i,v in pairs(game.Players:GetPlayers()) do children = v.Backpack:GetChildren() children:remove() end
Just learned about this kind of code and I am trying to remove everyone's tools from their backpacks. The code I was trying to write was supposed to get all the players, find their backpack, get everything that is in the backpack, and then remove it. Is there a better way to do this? The error code I receive tells me it is trying to remove a nil value. Ty for the help! :D
Well your issue is you aren't looping through the players stuff once you get the stuff. You can't exactly remove
children that way. Here is the fixed code, incase you need an example.
for i,v in pairs(game.Players:GetPlayers()) do children = v.Backpack:GetChildren() for i, v in pairs (children) do -- This loops through the player's stuff removing it. v:Destroy() end end
You can also instead of looping through children do :ClearAllChildren()
as this event is more efficient. The issue with it is that it doesn't remove the children. It changes the parent.
Hope this helped!
Sincerely, jmanrock123
Here's a fixed version of your script:
for _, player in pairs(game.Players:GetPlayers()) do for _, child in pairs(player:GetChildren()) do child:Destroy() end end
Here's what changed.
First, we changed the top line, which was:
for i,v in pairs(game.Players:GetPlayers()) do
to this:
for _, player in pairs(game.Players:GetPlayers()) do
The only real difference here is the naming scheme. Calling a variable _
is the common practice for a variable that you don't use in Lua. We also name the second variable player
, since that's the player object we're dealing with.
Next, we changed this:
children = v.Backpack:GetChildren() children:remove()
to this:
for _, child in pairs(player:GetChildren()) do child:Destroy() end
First of all, you can't call methods on the result of GetChildren
, since GetChildren
returns a table of objects. A table of objects doesn't have regular ROBLOX methods, so we have to iterate through it and perform actions on each one using another for loop.
Another key thing to note is how we use Destroy
instead of remove
in the modified version. remove
is a deprecated method that has garbage collection issues. (don't worry if you don't know what garbage collection means)
I hope this helps you out. Good luck!