Cloning item on death

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Debris = game:GetService("Debris")

local Tool = script.Parent
local deathConnection

local function onPlayerDeath(character)
    if deathConnection then return end

    local humanoid = character:FindFirstChild("Humanoid")
    if humanoid then
        deathConnection = humanoid.Died:Connect(function()
            local NewBook = ServerStorage.Resources.BearBook:Clone()
            NewBook.CollisionGroupId = game:GetService("PhysicsService"):GetCollisionGroupId(_G.CG_NCC)
            NewBook.Massless = false
            NewBook.CanCollide = true

            local characterPosition = character.PrimaryPart.Position
            NewBook.Position = characterPosition + Vector3.new(0, 3, 0)

            NewBook.Parent = workspace.Debris
            Debris:AddItem(NewBook, 60)
        end)
    end
end

local function connectDeathEvent()
    if deathConnection then
        deathConnection:Disconnect()
        deathConnection = nil
    end

    local parent = Tool.Parent
    if parent:IsA("Model") and parent:FindFirstChild("Humanoid") then
        onPlayerDeath(parent)
    elseif parent:IsA("Backpack") then
        local player = Players:GetPlayerFromCharacter(parent.Parent)
        if player and player.Character then
            onPlayerDeath(player.Character)
        end
    end
end

Tool.AncestryChanged:Connect(function(_, newParent)
    if newParent then
        connectDeathEvent()
    end
end)

I wanted to make so if the player that owns this tool dies it clones an item and puts it 3 studs over their character. But for some reason it copies the item many times and also only works when the player is equipping the item (aka parented to the character). I want for it to copy only one item and also clone it if the item is in the backpack

2 Likes

If the event is repeating itself for some reason than you can use :Once()
instead of :Connect().
It would also get rid of the need for :Disconnect() as well.

yeah that actually works nvm thanks

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