How detect if player touches a part with specific name dynamically?

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
2 Likes
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
1 Like

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

1 Like

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

2 Likes

When you say ‘dynamically’, what do you mean? Also, when you say ‘new parts are added’, are they parts in the vault?

If there are new parts you want to detect you could look into using the DescendantAdded event.

A debounce is going to be the most efficient way, any other way would take much more time, effort and memory

1 Like

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()

1 Like

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.

1 Like

I know what the problem is. I’ve stated it before

I’m looking for a solution for this problem, not why it happens

1 Like

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)

Just a quick idea, it hasn’t been tested.

2 Likes

Thank you! Your code has helped a lot. But instead using a loop, I used .ChildAdded

Also sorry about that. My explanation was very poor :stuck_out_tongue:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.