Here's a fixed version of your script.
local Supplies = workspace:FindFirstChild("Supplies")
if #Supplies:GetChildren() > 0 then
for _, child in pairs(Supplies:GetChildren()) do
child:Destroy()
end
end
wait(0.5)
local newSupplies = script.Parent.Supplies:Clone()
newSupplies.Parent = workspace
Here's a rundown of what changed:
I changed this part at the beginning
location=(game.Workspace)
children=location:FindFirstChild("Supplies")
numberofchildren=#children
supplies = script.Parent.Supplies
to the following:
local Supplies = workspace:FindFirstChild("Supplies")
All you really needed here was the "Supplies" object in the Workspace. The rest of the variables were unnecessary. Also, a key thing to note hear is the "local" keyword before the variable name ("Supplies"). For the most part, you should use local variables in your scripts. Among other benefits, local variables can be accessed faster than global variables.
Moving on, I changed this part of your code
if numberofchildren == 1 then
children:Destroy()
end
to this:
if #Supplies:GetChildren() > 0 then
for _, child in pairs(Supplies:GetChildren()) do
child:Destroy()
end
end
Since we removed some unnecessary variables, we first do a quick check on how many children Supplies has. If it has more than 0 children, we iterate through all of the children within Supplies and destroy them. What you previously tried to do is:
children:Destroy()
The reason that does not work is because GetChildren returns an array of all of the children of an object. You can't destroy an array of an object or call any ROBLOX-related functions on an array. That's why you need to iterate through the array and destroy all of its members.
Finally, I changed this
x = supplies:Clone()
x.Parent = game.Workspace
To this:
local newSupplies = script.Parent.Supplies:Clone()
newSupplies.Parent = workspace
I directly indexed script.Parent.Supplies because we removed the variable earlier.
The new method also uses a local, named variable. Like I already mentioned, most of your variables should be local. It's also a good practice for readability to name your variables appropriately, even if they're short-lived.
I hope this helped. Good luck!
1 comment
remove the '()' around the location, it may be making it harder to use.