luacloneroblox

Clone() not seeming to work when setting it's parent to the StarterPack


I have a local script that should add an item to the player's StarterPack when I call a function in it and provide the name of the item as a parameter.

local replicatedStorage = game:GetService("ReplicatedStorage")
local assets = replicatedStorage:WaitForChild("Assets")
local player = game.Players.LocalPlayer


local function addItem(itemName)

    local item = assets:FindFirstChild(itemName)
    
    if not item then return end
    
    print(item)
    print("Adding "..itemName.." to backpack!")
    
    item:Clone().Parent = player.Backpack

end

I tried replacing the item:Clone().Parent = player.Backpack with this:

    local clone = item:Clone()
    clone.Parent = player.Backpack

Which also doesn't add the item into the StarterPack.

No errors or warnings are thrown up. As you can see, I put some print() functions in there and here is what they print:

Cloth Tunic -- from the print(item)

Adding Cloth Tunic to backpack! -- from the other print

Cloth Trousers -- from the print(item)

Adding Cloth Trousers to backpack! -- from the other print

(The function gets called two separate times at the beginning of the game, once for each item in the inventory)

So I'm not sure why the items aren't being put into the StarterPack if the code is making to the Clone() function and the item names are correct.


Solution

  • One problem with this script is that it adds the item to the player's Backpack instead of their Starter Gear. The Backpack gets cleared whenever a player spawns, while StarterGear is persistent (see the Backpack docs).

    Another problem is that your code seems to be executing on a LocalScript, which is generally only appropriate when working with client-only objects (see the LocalScript docs). You should run it on a regular script in ServerScriptService instead.

    The following script will add a tool named "Tool" to each player's StarterGear when they join the game:

    local replicatedStorage = game:GetService("ReplicatedStorage")
    local assets = replicatedStorage:WaitForChild("Assets")
    
    local function addItem(player, itemName)
        local item = assets:FindFirstChild(itemName)
    
        if not item then return end
    
        item:Clone().Parent = player:WaitForChild("StarterGear")
    end
    
    game:GetService("Players").PlayerAdded:Connect(function(player) addItem(player, "Tool") end)
    

    (Of course, you can achieve a similar effect just by putting Tool into the StarterPack folder.)