I am trying to make a game, and when you rejoin, I want your owned items to go back into your backpack when I rejoin.
The datastore is saved correctly when I leave and rejoin, and the items owned value is saved, but when I rejoin the game, none of the items get cloned into my backpack.
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local MainStore = DataStoreService:GetDataStore("PlayerMainStore")
local ITEM_LIST = {"Baseball Batt", "Foil", "Lead", "Nail", "Siccors"}
local WeaponsFolder = ReplicatedStorage:WaitForChild("Weaponds")
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local cash = Instance.new("IntValue")
cash.Name = "Cash"
cash.Value = 0
cash.Parent = leaderstats
local ownedItems = Instance.new("Folder")
ownedItems.Name = "OwnedItems"
ownedItems.Parent = player
local success, data = pcall(function()
return MainStore:GetAsync(player.UserId)
end)
if not success or type(data) ~= "table" then
data = {}
end
-- Load cash
if data.Cash ~= nil then
cash.Value = data.Cash
end
-- Load owned items
local items = data.Items or {}
for _, itemName in ipairs(ITEM_LIST) do
local itemValue = Instance.new("BoolValue")
itemValue.Name = itemName
itemValue.Value = items[itemName] == true
itemValue.Parent = ownedItems
if itemValue.Value then
local weapon = WeaponsFolder:FindFirstChild(itemName)
if weapon then
weapon:Clone().Parent = player:WaitForChild("Backpack")
end
end
end
end)
local function savePlayerData(player)
local leaderstats = player:FindFirstChild("leaderstats")
local ownedItems = player:FindFirstChild("OwnedItems")
if not leaderstats or not ownedItems then return end
local cash = leaderstats:FindFirstChild("Cash")
if not cash then return end
local items = {}
for _, itemName in ipairs(ITEM_LIST) do
local item = ownedItems:FindFirstChild(itemName)
if item and item:IsA("BoolValue") then
items[itemName] = item.Value
end
end
local dataToSave = {
Cash = cash.Value,
Items = items
}
pcall(function()
MainStore:SetAsync(player.UserId, dataToSave)
end)
end
Players.PlayerRemoving:Connect(savePlayerData)
game:BindToClose(function()
for _, player in ipairs(Players:GetPlayers()) do
savePlayerData(player)
end
end)```
Sorry if what I am trying to explain is confusing. Thank you for helping.