Hello! I was trying to learn how to use CollectionService and I have one question about it. Basically, whenever I tag an instance, as you can see in my code below, and right after that call a GetTagged function, it doesn’t get the instance I tagged. If I put a wait() between these operatiions, it suddenly works. My question is, why?
local PL = game:GetService("Players")
local COLS = game:GetService("CollectionService")
local DEBRIS = game:GetService("Debris")
PL.PlayerAdded:Connect(function(player)
local char = player.Character or player.CharacterAdded:Wait()
if char then
print(char.Name)
COLS:AddTag(char:WaitForChild("Head"), "SUS")
--wait(1) - if I add a wait in there, it works. Otherwise, it doesn't.
for i, v in pairs(COLS:GetTagged("SUS")) do
print(v.Name)
DEBRIS:AddItem(v, 3)
end
end
end)
That is correct. You need to yield the script for a second or two and let the game know that a new tag is being created for that certain object, otherwise if you try looping through it instantly it will skip the item you just added. However if you wanted you can just get their head and delete it too like this
PL.PlayerAdded:Connect(function(player)
local char = player.Character or player.CharacterAdded:Wait()
if char then
print(char.Name)
COLS:AddTag(char:FindFirstChild("Head"), "SUS")
DEBRIS:AddItem(char:FindFirstChild("Head"), 3)
for i, v in pairs(COLS:GetTagged("SUS")) do
print(v.Name)
DEBRIS:AddItem(v, 3)
end
end
end)
Okay, thanks a lot. I know I could delete their head just with Debris but I wanted to practice a bit the CollectionService. Again, thanks to everybody who replied.
Yeah, unfortunately this is the only way you’d be able to do it instantly. Otherwise if you tagged this from another part in your script and called a function that loops through it, that would work. At least it should…