So, I am trying to use datastores for the first time, and using pcall I have found that I am doing something wrong with saving the player’s data. Basically, im just trying to save and load a value.
Here is the whole script, incase I am loading data wrong also;
local rep = game.ReplicatedStorage
local event = rep.RemoteEvent
local DataStoreService = game:GetService("DataStoreService")
local Data = DataStoreService:GetDataStore("Data")
game:GetService("Players").PlayerAdded:Connect(function(player)
local Value = Instance.new("IntValue")
Value.Parent = game.ServerStorage
Value.Value = 0
Value.Name = player.UserId
--load values
local data
local success, errormessage = pcall(function()
local data = Data:GetAsync(player.UserId.."-cash")
end)
if success then
local Value = game.ServerStorage:WaitForChild(player.UserId)
Value.Value = data
end
--change UI (you can ignore this, just a UI to show the players money)
while wait() do
local value = game.ServerStorage:WaitForChild(player.UserId)
event:FireClient(player, value.Value)
end
end)
--save when leaving
game.Players.PlayerRemoving:Connect(function(player)
local success, errormessage = pcall(function()
local playerUserId = player.UserId
local value = game.ServerStorage.playerUserId.Value
Data:SetAsync(player.UserId, value)
end)
if success then
print("save")
elseif errormessage then
print("error")
end
end)
I am just getting error and would like to know what I am doing wrong.
Im storing value inside of the server and using remote events to change it from localscripts to secure every players values. Do datastores only work when stored in the player? And an unrelated question, is storing values in the player safe from exploits?
The error is in how you’re searching ServerStorage in your PlayerRemoving save function.
When you search game.ServerStorage for ‘playerUserId’ the way you are with dot notation, it’s literally searching for a child of ServerStorage named ‘playerUserId’ instead of the name of the Player’s UserID.
To fix this, you should search using bracket notation:
local value = game.ServerStorage[playerUserId].value
That should retrieve the IntValue properly!
P.S. I would recommend saving player data like this in a Script on the server instead, it’ll help you out a lot in the future.