Help with removing unwanted parts in a plot building system

i have a plot building system, when you use the tool to click on a wall it removes that wall and insters a model to replace it, expanding the base, but if there is another model plot placed next to it the left and right walls of it will not be removed because it only checks the one that is click by the tool, how would i check if these parts exist and if so remove them?

my current code:

local function changewall(wall, isvisible)
	local function change(wall, isvisible)
		if isvisible == true then
			wall.CanCollide = true
			wall.CanQuery = true
			wall.CanTouch = true
			wall.Transparency = 0
		else
			wall.CanCollide = false
			wall.CanQuery = false
			wall.CanTouch = false
			wall.Transparency = 1
		end
	end
	
	if wall:IsA("BasePart") then
		if table.find(module.wallnametable, wall.Name) then
			change(wall, isvisible)
			end
	else
		for i, obj in pairs(wall:GetChildren()) do
			if obj:IsA("BasePart") then
				if table.find(module.wallnametable, obj.Name) then
					if not obj:FindFirstChild("AttachedTo") then
						local go = true
						for i, checkobj in pairs(wall.Parent:GetDescendants()) do
							if checkobj:IsA("ObjectValue") and checkobj.Name == "AttachedTo" then
								if checkobj.Value == obj then
									go = false
								end
							end
						end
						if go == true then
							change(obj, isvisible)
							end
					end
					end
				end
		end
	end
end

function module:SetUnitPosition(baseunit, newunit, direction)
	newunit.Flooring.CFrame = baseunit.Flooring.CFrame 
	local objval = Instance.new("ObjectValue")
	objval.Name = "AttachedTo"
	
	if direction == "Left" then
		newunit.Flooring.CFrame -= baseunit.Flooring.CFrame.ZVector * newunit.Flooring.Size.X
		
		changewall(newunit.RightWall, false)
		changewall(baseunit.LeftWall, false)
		objval.Value = baseunit.LeftWall
		objval.Parent = newunit.RightWall
	elseif direction == "Right" then
		
		newunit.Flooring.CFrame += baseunit.Flooring.CFrame.ZVector * newunit.Flooring.Size.X
		
		changewall(newunit.LeftWall, false)
		changewall(baseunit.RightWall, false)
		objval.Value = baseunit.RightWall
		objval.Parent = newunit.LeftWall
	elseif direction == "Back" then
		newunit.Flooring.CFrame += baseunit.Flooring.CFrame.XVector * newunit.Flooring.Size.X
		
		changewall(newunit.FrontWall, false)
		changewall(baseunit.BackWall, false)
		objval.Value = baseunit.BackWall
		objval.Parent = newunit.FrontWall
	elseif direction == "Front" then
		newunit.Flooring.CFrame -= baseunit.Flooring.CFrame.XVector * newunit.Flooring.Size.X

		changewall(newunit.BackWall, false)
		changewall(baseunit.FrontWall, false)
		objval.Value = baseunit.FrontWall
		objval.Parent = newunit.BackWall
	end
	
	changewall(newunit, true)
	changewall(baseunit, true)
end

(this part of the code manages hiding the parts to allow more plots to be created and the right position placing of them)

1 Like