I'm having trouble trying to wrap my mind around the best way to have a single script that's able to detect and interact with multiple different clickdetectors/touched parts at once.
For example, if I wanted to make multiple doors that had clickdetectors inside them and then have a single script that allowed me to open and close all these doors as freely as I wanted to, with as many doors as I wanted to, how would I go about it?
I tried this with a for loop that obtained all the parts with clickdetctors, but the problem is that they cannot act independently from each other, and the script would break if you attempted to open any other door. I'm not even sure if this is the most efficient method of going about it, but having multiple scripts that all basically do the same thing doesn't seem right to me.
Is it possible to do all this in a single script with maybe one or two functions?
At its base, this is all the code is:
click = script.Parent.ClickDetector click.MouseClick:Connect(function() local door = click.Parent if door.Transparency == 0 and door.CanCollide == true then door.Transparency = 1 door.CanCollide = false else door.Transparency = 0 door.CanCollide = true end end)
Any way to make multiple of these scripts into a single script?
You can make a folder in workspace called Doors
.
local doors = game.Workspace.Doors for i, v in pairs(doors:GetChildren()) do if v:IsA("BasePart") and v:FindFirstChildOfClass("ClickDetector") then local clickDetector = v:FindFirstChildOfClass("ClickDetector") clickDetector.MouseClick:Connect(function() if v.Transparency == 0 and v.CanCollide == true then v.Transparency = .5 v.CanCollide = false wait(2) -- Waiting 2 seconds for the door to be open and then close it v.Transparency = 0 v.CanCollide = true end end) end end
You need to put the doors that you want to open inside the Doors folder.
Sure there is a way!
function OnClick() local door = click.Parent if door.Transparency == 0 and door.CanCollide == true then door.Transparency = 1 door.CanCollide = false else door.Transparency = 0 door.CanCollide = true end local DetectorOne = --Define this local DetectorTwo = --Define this --Create as much variables as you want --Do this for every Detector: DetectorOne.Click:Connect(OnClick) DetectorTwo.Click:Connect(OnClick)
This surely also works with other Events such as Touched etc.