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

Created Instance wont destroy NewInstances? "TextButton.LocalScript attempt to call a nil value?"

It has something to do with line 17 - 20 with the error of "Players.snipperdiaper.PlayerGui. NewInstances!.TextButton.LocalScript:20: attempt to call a nil value"

local Button = script.Parent
local Spawning = false
Button.MouseButton1Click:Connect(function()
	
	if Spawning then
		while true do
			wait(0.2)
			local NewPart = Instance.new("Part")
			Spawning = true
			NewPart.Name = "NewDestruction"
			NewPart.Parent = workspace
			
			
		end
		
		
	else
		Spawning = false
		local DestroyP = game.Workspace:GetChildren("NewDestruction")
		DestroyP:Destroy()
	end
	end)

-Thanks in advance, snipperdiaper

2 answers

✓ Accepted answer

Fixed code:

local Button = script.Parent
local Spawning = false

Button.MouseButton1Click:Connect(function()
    if Spawning then
        while true do
            wait(0.2)
            local NewPart = Instance.new("Part")
            Spawning = true
            NewPart.Name = "NewDestruction"
            NewPart.Parent = workspace
        end
    else
      local DestroyP = workspace:GetChildren()
      for index, value in ipairs(DestroyP) do
         if value.Name == "NewDestruction" and value:IsA("Part") then
           value:Destroy() 
        end
     end
   end
end)

line 14: :GetChildren() will return a table specifically an array.

line 15: ipairs is used for arrays, and pairs is used for dictionaries.

line 16:A sanity check to check if value has a name "NewDestruction" and checks if it's a Part.

line 17: It'll run some code for each iteration of the array which is :Destroy().

I'm curious what you're trying to do because the while loop will loop forever yielding the current thread.

1 comment

0

Okay so I was trying to do a loop while the spawning was true (which would keep spawning the bricks until it was false) which I tried to fix but it didnt work.

The reason is because GetChildren() doesn't take any parameters. If you wanted to delete everything in a model, you could either delete the whole model, or iterate through the model's children. This is how you would do the second option.

local model = game.Workspace:FindFirstChild("NewDestruction")
if model then
	for i, part in pairs(model:GetChildren()) do
		part:Destroy()
	end
end

Hope this helps

2 comments

0

pairs is used for dictionaries, and ipairs is used for arrays. :GetChildren() returns an array

0

He wants to destroy objects in the workspace that are named "NewDestruction"

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