How would I destroy every model with the same name in workspace?

I am currently making a game but I have a vehicle cleanup script that I want to remove all vehicles when a value is changed but it only removes 1 of the cars from workspace how would I fix that here is my script: (I have 2 scripts this one just changes the value and removes the models)

local cars = game.ReplicatedStorage.Car

local Trucks = game.ReplicatedStorage.Truck

local CarStatus = game.ReplicatedStorage.Values.CarStatus

local Message = Instance.new("Message")

Message.Text = "Vehicle Cleanup In Progress..."

CarStatus.Changed:Connect(function()

wait(120)

Message.Parent = game.Workspace

wait(4)

Message.Parent = nil

CarStatus.Value = false

game.Workspace.Car:Remove()

game.Workspace.Truck:Remove()

end)

Thanks.

There are two ways: Loop through all children and check for name, or find a children with name until there is none left

local function ClearModelsWithName(name)
	for _, v in ipairs(workspace:GetChildren()) do
		if v.Name == name and v:IsA("Model") then
			v:Destroy()
		end
	end
end

With this code, you will get all children, loop through all of it, check if it matches the name, then destroys.

local function ClearModelsWithName(name)
	repeat local t = workspace:FindFirstChild(name)
		if t and t:IsA("Model") then
			t:Destroy()
		end
	until not t
end

This one however, tries to find a model with that name. If something is found, it destroys it and does the process again, if nothing is found, it stops.

The efficiency of both code depends on the amount of children. The first code is better if there are less children in the workspace, while the second code is better if there are less models to clear.

1 Like

Where would I put this in my code I pasted this inside of my function I had but it did nothing, Thanks.

You will call that function if you want to cleanup, like this.

local function ClearModelsWithName(name)
	repeat local t = workspace:FindFirstChild(name)
		if t and t:IsA("Model") then
			t:Destroy()
		end
	until not t
end

ClearModelsWithName("ModelName") -- Copy this code and change the name
3 Likes