So recently, I’ve been playing around with the CollectionService in order to have a single script for multiple copies of an object.
When I use the CollectionService for something simple like this kill brick, it works perfectly fine:
local CollectionService = game:GetService("CollectionService")
for i, lava in pairs(CollectionService:GetTagged("Deadly")) do
local function kill(otherPart)
local partParent = otherPart.Parent
local humanoid = partParent:FindFirstChild("Humanoid")
if humanoid then
humanoid.Health = 0
end
end
lava.Touched:Connect(kill)
end
However, when I do something a little more complex, such as this NPC follow script, it only works for just one copy of the NPC:
local CollectionService = game:GetService("CollectionService")
for i, enemy in pairs(CollectionService:GetTagged("NPC")) do
function FindTarget()
local maxDistance = 36
local target = nil
for i,v in pairs(workspace:GetChildren()) do
if v:FindFirstChild("Humanoid") then
if (v.Head.Position-enemy.Head.Position).magnitude < maxDistance then
target = v.Head
end
end
end
return target
end
while wait(0.1) do
local target = FindTarget()
if target then
enemy.Humanoid:MoveTo(target.Position)
end
end
end
I saw that a few other people had this issue in the past, but none of them seemed to provide me with a clear answer that I could apply to any object. Additionally, I tried several of my own rearrangements of the code, and it still wasn’t working for every copy that was tagged.
Also, both of the scrips above are regular scripts within ServerScriptService.