Datastore Problem

Soo I am trying to achieve a something like Pet Simulator or simulators in general Datastore. Like let’s say you click on a button and you buy a tool and then you leave the game but the tool will still be there, but I don’t know where to start and I got some code that I don’t know if it works or if it even makes sense, please help. Like simulators have that thing like it saves the tool your using and saves.

local DataStore = game:GetService("DataStoreService")
local Items = DataStore:GetDataStore("Items")
local PlayerItems = {}
local DefaultPlayerData = {}


game.Players.PlayerRemoving:Connect(function(player)
	pcall(function()
		Items:SetAsync(player.UserId.."Items", PlayerItems)
	end)
end)
local DataStore = game:GetService("DataStoreService")
local Items = DataStore:GetDataStore("Items")
local PlayerItems = {}
local DefaultPlayerData = {}

game.Players.PlayerAdded:Connect(function(player)
local success,errormessage = pcall(function()
local data = Items:GetAsync(player.UserId.."Items") --getting data
end)
if success then --check if the data successfully loads
PlayerItems = data --set your playeritems to the given saved data
end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local success,errormessage = pcall(function()
		Items:SetAsync(player.UserId.."Items", PlayerItems)
	end)
end)

Btw, thank you, now I’ve learned how pcall works.

1 Like

The best way to store player items would be to think of their items as a table of data.
When you want to equip their tools, create those tools using this data.
When you wish to save their data, just store the table to the database.

If you can’t figure out how to do this yourself. This post explains it:

Good luck, let me know if you got it working!

EDIT:
Make sure when you cache data on the server, to use a unique index for every player,
don’t just set the cached data to the data of a joining person because you would need
to access the Datastore every time you would want to get someone’s data.

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local ItemDatastore = DataStoreService:GetDataStore("Items")

local defaultItems = {}
local cachedItems = {}

Players.PlayerAdded:Connect(function(player)
  local data = {}
  local ok, msg = pcall(function()
    data = ItemDatastore:GetAsync(tostring(player.UserId))
  end)
  if not ok then
    player:Kick("Your data failed to load, please rejoin!")
  else
    cachedItems[tostring(player.UserId)] = data or defaultItems
  end
end)
2 Likes