Players did not get exp and money after killed an npc (Collection Service)

So i wanna make like when player kills an npc it will get rewards but the code below doesnt work.

I’m also new to collection service

local CollectionService = game:GetService("CollectionService")

local TagPart = CollectionService:GetTagged("NPCRewards")

local humanoid = script.Parent:WaitForChild("Humanoid")

function Died()
    game.ServerStorage.GiveExp:Fire(50, humanoid:FindFirstChild("creator").Value)
    wait(0.1)

    local tag = humanoid:FindFirstChild("creator")
    if tag ~= nil then
        if tag.Value ~= nil then
            local Coins = tag.Value:FindFirstChild("Money")
            local Exp = tag.Value:FindFirstChild("Exp")
            if Coins ~= nil then
                Coins.Value = Coins.Value + 10
            end
            if Exp ~= nil then
               Exp.Value = Exp.Value + 10
            end
        end
    end
    script.Parent:Destroy()
end

for _, TagParts in pairs(TagPart) do
    humanoid.Died:Connect(Died)
    Died(TagParts)
end

Also here’s the error
image

1 Like

Check if “script.Parent” has “Humanoid” as a child or not :slight_smile: And also, you shouldn’t retrieve/get (I can’t find a suitable word) humanoid too soon since it usually hasn’t been loaded yet.

1 Like

the for loop is not active put it in the run service

local RunService = game:GetService("RunService")
 
 
RunService.RenderStepped:Connect(function()
	for _, TagParts in pairs(TagPart) do
        humanoid.Died:Connect(Died)
        Died(TagParts)
    end
end)

I’ve tried it out,

but still doesnt work :sad:

I already parent it, but still doesnt work.

add TagPart to the ()
try this

still doesn’t work also even though i already parent it on the npc

Humanoid usually takes more time to load than the other parts of an NPC/player’s character so retrieving it too soon may output an error, maybe. There was a post somewhere that said this, as I remember.