local DataStoreService = game:GetService("DataStoreService") local myDataStore = DataStoreService:GetDataStore("myDataStore") wait(1) game.Players.PlayerAdded:Connect(function(plr) local data local success, errormessage = pcall(function() data = myDataStore:SetAsync(plr.UserId, game.ReplicatedStorage[plr.Name.."Stats"].Coins.Value) end) if success then print("Data Loaded!") game.ReplicatedStorage[plr.Name.."Stats"].Coins.Value = data else print("Data didn't Loaded Successfully!") end end) game.Players.PlayerRemoving:Connect(function(plr) local success, errormessage = pcall(function() myDataStore:SetAsync(plr.UserId, game.ReplicatedStorage[plr.Name.."Stats"].Coins.Value) end) if success then print("Data Successfully Saved!") else print(errormessage) print("There was an error while saving game!") end end)
What's wrong with this script? Please Help Me.
Improvements
Use WaitForChild()
to make sure an instance exists before using it
Use GetService()
for ReplicatedStorage
and Players
Issues
When Loading the Data, you are using SetAsync(key, value) when you should be using GetAsync(key)
Revised Server Script
local DataStoreService = game:GetService("DataStoreService") local myDataStore = DataStoreService:GetDataStore("myDataStore") local repst = game:GetService("ReplicatedStorage") game:GetService("Players").PlayerAdded:Connect(function(plr) local pdata = repst:WaitForChild(plr.Name.."Stats") local success, errormessage = pcall(function() myDataStore:GetAsync(plr.UserId) end) if success then local data = myDataStore:GetAsync(plr.UserId) if data then print("Data Loaded!") for index, value in pairs(pdata:GetChildren()) do value.Value = data[value.Name] end else print("No Data") end else warn(errormessage) print("Data didn't Load Successfully!") end end) game:GetService("Players").PlayerRemoving:Connect(function(plr) local pdata = repst:WaitForChild(plr.Name.."Stats") local data = {} for index, value in pairs(pdata:GetChildren()) do data[value.Name] = value.Value end local success, errormessage = pcall(function() myDataStore:SetAsync(plr.UserId, data) end) if success then print("Data Successfully Saved!") else warn(errormessage) print("There was an error while saving game!") end end)