I bearly ever use datastores, and want my inventory UI to save all the objects placed in a folder in my playergui.
It always fails afterwards.
the script I’m using:
--// Services
local Players = game:GetService("Players")
local DSS = game:GetService("DataStoreService")
--// Variables
local DS = DSS:GetOrderedDataStore("Items2")
--// Function
local function OnPlayerAdded(player)
local plr_key = "id_"..player.UserId
local success, data = pcall(function()
return DS:GetAsync(plr_key)
end)
local DataFiles = {}
if success then
DataFiles = data or {}
end
for i, obj in pairs(DataFiles) do
obj.Parent = player.PlayerGui.Inventory
end
end
local function OnPlayerRemoving(player)
local plr_key = "id_"..player.UserId
local success, result = pcall(function()
return DS:SetAsync(plr_key, player.PlayerGui.Inventory:GetChildren())
end)
if not success then
warn(result)
end
end
local function OnServerShutdown()
for _, player in Players:GetPlayers() do
local plr_key = "id_"..player.UserId
local success, result = pcall(function()
return DS:SetAsync(plr_key, player.PlayerGui.Inventory:GetChildren())
end)
if not success then
warn(result)
end
end
end
--// Connections
Players.PlayerAdded:Connect(OnPlayerAdded)
Players.PlayerRemoving:Connect(OnPlayerRemoving)
game:BindToClose(OnServerShutdown)
Sorry for being late, but, I ended up reworking most of the system and figuring it out myself, thanks anyway ;-;
--// Services
local Players = game:GetService("Players")
local DSS = game:GetService("DataStoreService")
--// Variables
local DS = DSS:GetDataStore("Items6")
--// Function
local function OnPlayerAdded(player)
player.PlayerGui:WaitForChild("Inventory").Parent = player
local plr_key = "id_"..player.UserId
local success, data = pcall(function()
return DS:GetAsync(plr_key)
end)
local DataFiles = {}
if success then
DataFiles = data or game.HttpService:JSONEncode({})
end
for i, obj in pairs(game.HttpService:JSONDecode(DataFiles)) do
if game.ServerStorage.Drops:FindFirstChild(obj) then
game.ServerStorage.Drops:FindFirstChild(obj):Clone().Parent = player.Inventory
else
warn("couldnt find" .. obj)
end
end
end
local function OnPlayerRemoving(player)
local plr_key = "id_"..player.UserId
local success, result = pcall(function()
local TBL = {}
for i, obj in pairs(player.Inventory:GetChildren()) do
table.insert(TBL, obj.Name)
end
TBL = TBL
return DS:SetAsync(plr_key, game.HttpService:JSONEncode(TBL))
end)
if not success then
warn(result)
end
end
local function OnServerShutdown()
for _, player in Players:GetPlayers() do
local plr_key = "id_"..player.UserId
local success, result = pcall(function()
local TBL = {}
for i, obj in pairs(player.Inventory:GetChildren()) do
table.insert(TBL, obj.Name)
end
TBL = TBL
return DS:SetAsync(plr_key, game.HttpService:JSONEncode(TBL))
end)
if not success then
warn(result)
end
end
end
--// Connections
Players.PlayerAdded:Connect(OnPlayerAdded)
Players.PlayerRemoving:Connect(OnPlayerRemoving)
game:BindToClose(OnServerShutdown)