What do you want to achieve?
I want to run a for loop to detect when any click detectors are activated, including click detectors added after the loop is run.
Is there a way to do this without lagging out my game?
What is the issue?
It doesn’t detect the click detectors added after the loop is run (understandably).
What solutions have you tried so far?
I tried running the loop every time a child was added to workspace, if the child was a click detector. I’m not sure why, but this broke it. Terribly. I tried googling how to achieve this, but nothing.
for i, Pickable in pairs(workspace:GetDescendants()) do
if Pickable.Name == "Pickable" then
Pickable.MouseClick:Connect(function()
print("Okay")
end)
end
end
I recommend collection services. You can tag the click detectors and detect when only the click detectors are added without needing to loop through the entire workspace and cause lag.
local function ConnectClickDetector(Pickable)
Pickable.MouseClick:Connect(function()
print("Okay")
end)
end
for i, Pickable in pairs(workspace:GetDescendants()) do
if Pickable.Name == "Pickable" then
ConnectClickDetector(Pickable)
end
end
workspace.DescendantAdded:Connect(function(obj)
if obj:IsA'ClickDetector' and obj.Name == 'Pickable' then
ConnectClickDetector(obj)
end
end)
Besides using the ChildAdded event for the workspace, you could use attributes to detect whenever a ClickDetector is added to the workspace.
How I would do it is I’d add a boolean attribute to the workspace, then set it to false. Then in whatever script that controls when a new ClickDetector is added to the workspace, I would also set the workspace’s boolean attribute that we added earlier to “true” by doing workspace:SetAttribute(“NameOfAttribute, true”) after you have parented the new ClickDetector to the workspace.
Then I would use the GetAttributeChangedSignal() function to detect when the Attribute’s value is changed to true, and then put the for loop function you had above inside this function.
I don’t really see any reason why ChildAdded wouldn’t work, so I’m guessing you implemented incorrectly somehow.
The best way to do this would be to use the Changed event on the ClickDetector. This event will be triggered whenever the ClickDetector is added, removed, or modified. You can then use this event to update the loop that you have to include the new ClickDetector.
workspace.DescendantAdded:Connect(function(descendant)
if descendant:IsA("ClickDetector") then
descendant.MouseClick:Connect(function()
print("Okay")
end)
end
end)