Hey guys, so I just learnt datastores, and I made my very own datastore script! Please give me feedback on it!
CODE:
--[[IMPORTANT: Please publish the game first!!! After publishing, go to Game Settings > Security >
Allow Studio Access to API Services, and turn it on.
]]
local DS = game:GetService("DataStoreService")
local Players = game.Players
local DATA_STORE = DS:GetDataStore("Points", "Points that each individual player has.")
local function setupStats(player)
--creating leaderstats folder
local ls = Instance.new("Folder")
ls.Name = "leaderstats"
ls.Parent = player
--creating the points object
local points = Instance.new("NumberValue")
points.Name = "Points"
local success, errorMessage = pcall(function()
--datastores might fail, so we wrap it on a pcall
points.Value = DATA_STORE:GetAsync(tostring(player.UserId).."-points")
end)
if not success then
warn("Datastore failed: "..errorMessage)
end
points.Parent = ls
end
game.Players.PlayerAdded:Connect(setupStats)
local function savePoints(player)
local success, errorMessage = pcall(function()
DATA_STORE:SetAsync(tostring(player.UserId).."-points", player.leaderstats.Points.Value)
end)
if not success then
warn("Failed to save player points: "..errorMessage)
end
end
game.Players.PlayerRemoving:Connect(savePoints)
This is a really basic Datastore that looks like you followed an AlvinBlox tutorial to create.
Even though I don’t often use Datastores, that doesn’t mean I don’t know their fundamentals. If you’re looking for complex Datastores like storing items, instances, etc I suggest you look into both HttpService(look into JSONEncode:()/JSONDecode:()) & ProfileService
This solution will work, but it won’t if you want to expand your game. You should save a whole dictionary containing their data, instead of a single value. What if you added gems? An inventory? Codes? You would need more room.
It should also return the value instead of setting it in the pcall. The second value returned is the result. If the first value is true, then it will be the return value. Otherwise, it’s the error.
I suggest using a module called ProfileService or DataStore2, your script has huge flaws in it:
If their player stats fail to load initially, there is a chance it will save when they leave. Thus leading to data loss.
You only save their points when they leave. I could play the game for 5 hours, rack up many points, and then lose it all when I leave if the data store fails.
Looping back to #2, because there’s no periodic autosaving, if the server abruptly ends you will also lose data.
Scopes shouldn’t be a long sentence. It also appears that they are deprecated and shouldn’t be used.