Search code examples
eventsclonerobloxluau

How do I make a clone of an object when an NPC dies?


I am trying to make it so that you have to kill an NPC to get the code to a vault. This is my first time making anything in roblox studio, so forgive me if this seems stupid.

After reading the API documentation, I made this. I basically just copied and pasted some stuff and replaced stuff that I thought I needed to replace:

`

local Humanoid = script.parent:WaitForChild(“Guard”)

(This is not part of the original code:) I put^ the name of the NPC I'm using, in this case the Guard.
local original = workspace.VaultCode

(This is not part of the original code:) Here^ I replaced something like part or whatever with the part name VaultCode. It doesn't seem right, but idk.

local copy = original:Clone()
Humanoid.Died:Connect(function()
    copy.Parent = original.Parent
    copy:SetPrimaryPartCFrame(CFrame.new(0, -300, 0))
end)

` I expected it to create a clone of the part Vaultcode when the NPC Guard died, but nothing happened.

I also tried looking this question up and made something similar, but I deleted it and forgot what I did. All I know is it didn't work.


Solution

  • The things that stand out to me in your code are,

    • it looks like you have found the NPC's character model, but not their Humanoid,
    • you only clone the VaultCode object once, and
    • you spawn the object really far underground.

    It's possible that if the object isn't Anchored, that it is immediately falling down to the kill-plane (around -500 studs) and being immediately destroyed. And since you're only cloning it once, you are trying to set the position of an object that no longer exists.

    To fix this, try spawning the object where the NPC died instead, and clone a new one every time.

    I am assuming that this Script is located in the Workspace, not the NPC character model.

    -- find the VaultCode object
    local VaultCode : Model = workspace.VaultCode
    
    -- find the NPC and its humanoid
    local Humanoid : Humanoid = script.Parent:WaitForChild(“Guard”).Humanoid
    
    -- listen for when the Humanoid dies
    Humanoid.Died:Connect(function()
        -- create a copy of the vault code where the NPC died
        local npcCFrame = Humanoid.Parent:GetPivot()
    
        local copy = original:Clone()
        copy:SetPrimaryPartCFrame(npcCFrame)
        copy.Parent = original.Parent
    end)