How to make For loop detect newly added part

I have a local script that has a for loop that loops through all parts that has a tag.
It only detects 1 part even though there is a bunch of parts that has the same tag.

Mock up of my local script:

connection = RunService.Hearbeat:Connect(function()
for _, part in pairs (CollectionService:GetTagged("tag") do
    local distance = (part.location - humanoidrootpart.position).Magnitude

    if distance < 10 then -- if the distance between the player and the part is close
       print("CLOSE") 
    end

end
end)
-- I manually wrote the code here. I didn't paste it from studio --

When a new part is added, it only detects that newly added part and it doesn’t detect the old parts

I tried adding " Instance Added Signal " but it just made the game lag and still didn’t work

I recommend declaring distance outside of the runservice code block for performance optimization, about your issue, the code looks fine to me, are you sure those parts actually have the tag? This code will print CLOSE only for parts closer than 10 studs to the root part of the local player.

It seems that your for loop is not detecting all parts because you are using pairs instead of ipairs to iterate over the tagged parts. pairs will iterate over all elements in a table, but it does not guarantee the order of iteration. On the other hand, ipairs will iterate over the table in numerical order, starting from 1. This might be important if you want to detect all parts with the same tag in a consistent way.

By the way, you might want to connect a function to the Touched event of each part. This way, you can handle what happens when a player touches a part with a specific tag.

connection = RunService.Hearbeat:Connect(function()
  for _, part in ipairs(CollectionService:GetTagged("tag")) do
    local distance = (part.location - humanoidrootpart.position).Magnitude
    if distance < 10 then
      print("CLOSE")
    end

    part.Touched:Connect(function(hit)
      print("TOUCHED")
    end)
  end
end)
1 Like

What are you trying to do? Like?

1 Like

You can make a seperate function which detects new parts being added

[where you store the parts].DescendantAdded:Connect(function(part)
--tag the part using collection service
end)

This means you will need to store all the parts in a specific folder/model so it doesn’t detect any players body parts when they join and their character is added to the workspace.