How to make it so that there can be multiple doors

I made a different post on how to make a door that opens when you step on a button but I wanted there to be multiple doors the code didn’t seem to work though

explorer for doors

Screen Shot 2022-04-15 at 2.10.19 PM

explorer for buttons

Screen Shot 2022-04-15 at 2.14.04 PM

code to open door1

-- local Door = workspace.DoorModel:WaitForChild("Door1")
local ButtonDebounce = false
local DoorDebounce = false
script.Parent.Touched:Connect(function(hit) 
	if hit.Parent:FindFirstChildWhichIsA("Humanoid") and not DoorDebounce and not ButtonDebounce then
		DoorDebounce = true 
		ButtonDebounce = true 
		Door.CanCollide = false 
		Door.Transparency = 1 
		wait(1)
		DoorDebounce = false 
		ButtonDebounce = false 
	end
end)

and for door2 I change door1 to door2 and so on

sry for hurting your eyes with light mode im on a different computer that has light mode locked on lol

Right now you have the “Door” variable commented out so it’s not going to do anything. Additionally the way your hierarchy is set up you’re also going to have the change the door model in the path for the “Door” variable.

Those changes should make it so your script is functioning, but there are ways you could improve it. Currently you have to have a script for each door but you could improve this so you only need one script. Using the Tag Editor plugin you can add a CollectionService tag to each of your door buttons. These tags just allow you to easily get a table with all of the tagged instances.

A video example of tagging the buttons

Before we can write the new script you’re going to need to create an ObjectValue as a child of each button and set its value to the corresponding door. Now in a new script in either the ServerScriptService or still in the Workspace you can get all of the items tagged with the door button tag like this.

local CollectionService = game:GetService("CollectionService")
local doorButtons = CollectionService:GetTagged("DoorButton")

Now you can loop through these buttons with an ipairs loop.

for _, button in ipairs(doorButtons) do

end

And inside of this loop you can get the door from that ObjectValue you created earlier and then copy over pretty much the same code you had before.

local CollectionService = game:GetService("CollectionService")

local doorButtons = CollectionService:GetTagged("DoorButton")

for _, button in ipairs(doorButtons) do
	local doorDebounce = false
	local buttonDebounce = false
	local door = button.Door.Value
	
	button.Touched:Connect(function(hit)
		if hit.Parent:FindFirstChildWhichIsA("Humanoid") and not doorDebounce and not buttonDebounce then
			doorDebounce = true
			buttonDebounce = true
			door.CanCollide = false
			door.Transparency = .75
			task.wait(1)
			door.CanCollide = true
			door.Transparency = 0
			doorDebounce = false
			buttonDebounce = false
		end
	end)
end
2 Likes