Hey everyone, I’m trying to detect if the player touches a part with a specific name, to perform a vault action. However I can’t find a way to do this dynamically, so if new parts are added, the script will also consider those.
Also, how to fix it, so the event isn’t fired multiple times? Preferably not using a debounce.
for _, v in pairs(workspace.Vaulting_Parts:GetChildren()) do
v.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and v.Name == "Vault08" then
print("touched")
end
end)
end
for _, v in pairs(workspace.Vaulting_Parts:GetChildren()) do
v.Touched:Connect(function(hit)
local Humanoid = hit.Parent:FindFirstChild("Humanoid")
--if Humanoid and v.Name == "Vault08" then
-- print("touched")
--end
if Humanoid then
print("touched",v)
end
end)
end
Sorry, but this code does exactly what mine does, with the difference that it prints the name of the part that is being touched, which I already now, since I created a condition for it
You should look into CollectionService, with this you can add new parts to the “collection” and also detect on the client when new parts are added to the tag
By dynamically I mean if new parts with the name of “Vault08” are added to the folder. The script should be able to consider these new parts, which does not happens with :GetChildren()
You’re iterating over a previously received amount. GetChildren() returns a table of the children of the object at the time of use. So if you used it, and then added a part to the folder, it wouldn’t be added to the table.
Sorry, “Doesn’t happen with GetChildren()” was kind of vague… nevermind.
In terms of a solution, you could keep your loop, but use a coroutine.
local loopVaultParts = coroutine.create(function()
for _, v in ipairs(workspace.Vaulting_Parts:GetChildren()) do
--touched code here
end
end)
coroutine.resume(loopVaultParts)
workspace.Vaulting_Parts.ChildAdded:Connect(function(child)
child.Touched:Connect(function(hit)
--do stuff
end)
end)