How do I make the script work for multiple model with the same name?

Hi, I was trying to make a local script that works for all model named “Door”. However, all of my attempts only resulted in the script only working for 1 door. I have tried WaitForChild() and GetDescendants() but still failed. Please help me.

local TweenService = game:GetService("TweenService")

for _,object in pairs(game.Workspace:GetDescendants()) do
	if object:IsA'Model' then
		if object.Name == "Door" then
			door = object
		end
	end
end

local prompt = door.Base.ProximityPrompt
local hinge = prompt.Parent.Parent.Doorframe.Hinge
local openandclose = script["Open/Close"]

local goalOpen = {}
goalOpen.CFrame = hinge.CFrame * CFrame.Angles(0, math.rad(45), 0)

local goalClose = {}
goalClose.CFrame = hinge.CFrame * CFrame.Angles(0, 0, 0)

local Info = TweenInfo.new(1)
local Open = TweenService:Create(hinge, Info, goalOpen)
local Close = TweenService:Create(hinge, Info, goalClose)

prompt.Triggered:Connect(function()
	if prompt.ActionText == "Close" then
		Close:Play()
		openandclose:Play()
		prompt.ActionText = "Open"
		prompt.Enabled = false
		wait(1)
		prompt.Enabled = true
	else
		Open:Play()
		openandclose:Play()
		prompt.ActionText = "Close"
		prompt.Enabled = false
		wait(1)
		prompt.Enabled = true
	end
end)

2022-03-28

1 Like

Have all your code inside the for loop, because the prompt variable defined outside of it is only one door’s prompt

local TweenService = game:GetService("TweenService")

for _,object in pairs(game.Workspace:GetDescendants()) do
	if object:IsA'Model' then
		if object.Name == "Door" then
            local prompt = object.Base.ProximityPrompt
            local hinge = prompt.Parent.Parent.Doorframe.Hinge
            local openandclose = script["Open/Close"]

            local goalOpen = {}
            goalOpen.CFrame = hinge.CFrame * CFrame.Angles(0, math.rad(45), 0)

            local goalClose = {}
            goalClose.CFrame = hinge.CFrame * CFrame.Angles(0, 0, 0)

            local Info = TweenInfo.new(1)
            local Open = TweenService:Create(hinge, Info, goalOpen)
            local Close = TweenService:Create(hinge, Info, goalClose)

            prompt.Triggered:Connect(function()
	                        if prompt.ActionText == "Close" then
		                        Close:Play()
		                        openandclose:Play()
		                        prompt.ActionText = "Open"
		                        prompt.Enabled = false
		                        wait(1)
		                        prompt.Enabled = true
	                        else
		                        Open:Play()
		                        openandclose:Play()
		                        prompt.ActionText = "Close"
		                        prompt.Enabled = false
		                        wait(1)
		                        prompt.Enabled = true
	                         end
                        end)
		end
	end
end
3 Likes

Wow, that works, thanks a lot!

1 Like