Loop works only if there is one structure placed

So I’m making a factory game and my goal, for now, is to pass electricity from a structure to another.

This is the script for the electricity stuff:

local currentAttachment = script.Parent:WaitForChild("Attachment")
local currentModel = currentAttachment:FindFirstAncestor("CoalGenerator")
local currentModelElectricity = currentModel:GetAttribute("Electricity")
local wiresFlder = script:FindFirstAncestor("Structures"):FindFirstAncestorWhichIsA("Folder"):FindFirstChild("Wires")

local otherAttachment

local connected = false
local active

local wires = {}

while wait(0.5) do
	active = currentModel:GetAttribute("Active")
	
	if active and not connected	then
		for _,v in pairs(wiresFlder:GetDescendants()) do
			if v.Attachment0 == currentAttachment then
				connected = true
				otherAttachment = v.Attachment1
				if otherAttachment:FindFirstAncestor("CenterPoint") then
					local otherModel = otherAttachment:FindFirstAncestor("CenterPoint")
					local otherModelElectricity = otherModel:GetAttribute("Electricity")

					otherModel:SetAttribute("Electricity", otherModelElectricity + currentModelElectricity)
					print(currentModelElectricity.." | "..tostring(connected))
				end
			elseif v.Attachment1 == currentAttachment then
				connected = true
				otherAttachment = v.Attachment0
				if otherAttachment:FindFirstAncestor("CenterPoint") then
					local otherModel = otherAttachment:FindFirstAncestor("CenterPoint")
					local otherModelElectricity = otherModel:GetAttribute("Electricity")

					otherModel:SetAttribute("Electricity", otherModelElectricity + currentModelElectricity)
					print(currentModelElectricity.." | "..tostring(connected))
				end
			else
				connected = false
			end
		end
	elseif not active and connected then
		local otherModel = otherAttachment:FindFirstAncestor("CenterPoint")
		local otherModelElectricity = otherModel:GetAttribute("Electricity")
		
		otherModel:SetAttribute("Electricity", otherModelElectricity - currentModelElectricity)
		connected = false
	end
end

The problem with this script is that it works only if there is one structure attached to another. Like this:

If instead there are multiple structures attached to another only the last one attached work as intended, the others keep adding electricity.


I tried to fix it multiple times now but I can’t find the error.

I hope that I explained it well.
Any help will be appreciated. Thanks