How can I use one script across multiple buttons im my script

I’m trying to use this script with every single button that would be attached to a door, collected using a collection service. With my current script it only works for my first door. I’ve tried 2 foor loops but I get a different error, and I’ve also tried making a tag as well.

-- Main Script
local doorModule = require(game:GetService("ReplicatedStorage").DoorModule)

local collectionService = game:GetService("CollectionService")
local doors = collectionService:GetTagged("Door") -- A list of all instances with tag door
local buttons = {}

for i, door in ipairs(doors) do
	local newDoor = doorModule.new(door)
	-- table.insert(doorModule.doors, newDoor)
	table.insert(buttons, newDoor[i].Parent.Button)
	
	if newDoor[i].Parent.Button then
		newDoor[i].Parent.Button.ClickDetector.MouseClick:Connect(function()
			doorModule:toggleState(newDoor[i])
		end)
	end
	
end

This is my main script above and my module script below.

local tweenService = game:GetService("TweenService")

local doorModule = {}
doorModule.__index = doorModule

doorModule.doors = {} -- A table for all of our doors
doorModule.closed = false
doorModule.closeTime = 1

function doorModule.new(door)
	-- local doors = setmetatable({}, doorModule)
	table.insert(doorModule.doors, door)
	
	-- doors[i] = door
	-- print(doors)
	print(doorModule.doors)
	return doorModule.doors
end

function doorModule:createTween(doorModel, tweenGoals)
	local tweenInfo = TweenInfo.new(self.closeTime, Enum.EasingStyle.Circular, Enum.EasingDirection.InOut)
	local tween = tweenService:Create(doorModel, tweenInfo, tweenGoals)
	
	return tween
end
  
function doorModule:toggleState(doorModel)
	if not self.closed then
		local tween = self:createTween(doorModel, {Position = doorModel.Parent.Closed.Position})
		tween:play()
		print("Door has opened")
	else
		local tween = self:createTween(doorModel, {Position = doorModel.Parent.Open.Position})
		tween:play()
		print("Door has closed")
	end
	
	self.closed = not self.closed
end

return doorModule
1 Like

You know, thing you trying to do is that every button connected to the specific door can interact with it, you can achieve it with one loop and some type of assignment like object value or table with buttons, then loop through doors and then inside loop through buttons, you can use naming system that doorA and buttonA or something. Then simply connect function to buttons and you’ll be ok

Okay, so what I’m hearing is 3 different loops? So one loop to assign a table with buttons then a loop for the doors, and a nested loop for the buttons?

1 Like

Kind of, you have to first get all doors, then all buttons related to specific door and then use function in loop to open doors or something