Why the while don't work in this script

So whenever i try to use this script the “while” function doesn’t work and i tried making values like the “BoolValue” or just creating the value on the script, but i can’t find a solution

Script:

local Workspace = game:GetService("Workspace")
local Detector = Workspace.Desaparecer:WaitForChild("Detector")
local jugador = game.Players.LocalPlayer
local DetectorTocado = false


--abajo derecha adelante
--arriba izquierda atras
local Piezas = game.Workspace.Desaparecer.Piezas:GetDescendants()
local PiezaBorrandose = Piezas[math.random(1,#Piezas)]

print("comenzando funcion")
Detector.Touched:Connect(function(hit)
	Detector.CanTouch = false
	print("Funcion")
	DetectorTocado = true
	print("Tocado")
end)

while DetectorTocado == true do
	print("While")
	PiezaBorrandose:Destroy()
	print("PiezaBorrada")
	local PiezaBorrandose = Piezas[math.random(1,#Piezas)]
	print("seleccionando")
end

what is supossed to do is when a part is touched it starts destroying parts in a table

1 Like

You can just loop through the table after detecting touch.

Fix:

local Workspace = game:GetService("Workspace")
local Detector = Workspace.Desaparecer:WaitForChild("Detector")
local jugador = game.Players.LocalPlayer
local DetectorTocado = false


--abajo derecha adelante
--arriba izquierda atras
local Piezas = game.Workspace.Desaparecer.Piezas:GetDescendants()
local PiezaBorrandose = Piezas[math.random(1,#Piezas)]

print("comenzando funcion")
Detector.Touched:Connect(function(hit)
	Detector.CanTouch = false
	DetectorTocado = true
	
	for _, Instance_ in Piezas do
		Instance_:Destroy()
	end
end)

my bad, i forgot to mention that is destroy the objects in between a wait time, also your script doesn’t destroy all of the instances that exists

Put the loop in a function:

local Workspace = game:GetService("Workspace")
local Detector = Workspace.Desaparecer:WaitForChild("Detector")
local jugador = game.Players.LocalPlayer
local DetectorTocado = false


abajo derecha adelante
arriba izquierda atras
local Piezas = game.Workspace.Desaparecer.Piezas:GetDescendants()
local PiezaBorrandose = Piezas[math.random(1,#Piezas)]

local function Loop()
	while DetectorTocado == true do
		task.wait() -- so your game doesn't lock up
		print("While")
		PiezaBorrandose:Destroy()
		print("PiezaBorrada")
		local PiezaBorrandose = Piezas[math.random(1,#Piezas)]
		print("seleccionando")
	end
end

print("comenzando funcion")
Detector.Touched:Connect(function(hit)
	Detector.CanTouch = false
	print("Funcion")
	DetectorTocado = true
	print("Tocado")
	Loop()
end)


i tried this and i got this error

Replace: PiezaBorrandose:Destroy() with PiezaBorrandose = {}

but what i try to achieve is that the instances destroy, not just that the “while” works