✓ Accepted answer
No you are using it correctly, However you shouldn't save your datastore under playeruserid alone. Add something to the end of player userid. This an old code of mine for a DataStore very similar to yours.
local STOREDATAPLZ = {}
local storage = game:GetService("DataStoreService"):GetDataStore("Test")
game.Players.PlayerAdded:connect(function(player)
local Stats = Instance.new("StringValue", player)
Stats.Name = "leaderstats"
local test = Instance.new("NumberValue", Stats)
test.Name = "test"
test.Value = storage:GetAsync(player.userId.."-test") or 0
test.Changed:connect(function()
storage:SetAsync(player.userId.."-test", test.Value)
print("Stats saved :)")
end)
end)
game.Players.PlayerRemoving:connect(function(plr)
local testValue = plr.leaderstats.test
storage:SetAsync(plr.userId.."-test", testValue.Value)
print ("Data saved!")
end)
return STOREDATAPLZ
Notice how I added "-test" to the end of the player.userId so that the DataStoreService could find the specific number.
Edit: Also, the PlayerRemoving might not work on studio even if you have API Services activated, I remember when I wrote that script it did not, so I added the .Changed function
1 comment
When the server closes PlayerRemoving does not fire so you also need to save data on close. https://wiki.roblox.com/index.php?title=API:Class/DataModel/OnClose