Note: I am messing around datastore very recently and I am noob in it so there maybe many mistakes in my code
Code:
--Made By Beastcraft_Gaming--
--30/10/20--
print("Script is working");
--Variables
--Services
local Players = game:GetService("Players");
local DataStoreService = game:GetService("DataStoreService");
local MyDataStore = DataStoreService:GetDataStore("CashDataStore");
--functions
local function UpdateGui(player)
local Gui = player:WaitForChild("leaderstats"):WaitForChild("Cash");
local Value = MyDataStore:GetAsync("Cash"..player.UserId);
Gui.Value = Value;
end
local function OnPlayerAdded(player)
UpdateGui(player);
local leaderstats = player:WaitForChild("leaderstats");
local Data
local success, errormessage = pcall(function()
Data = MyDataStore:GetAsync("Cash"..player.UserId);
end)
if success then
if Data then
leaderstats:WaitForChild("Cash").Value = Data;
else
leaderstats:WaitForChild("Cash").Value = 0;
end
else
warn(errormessage)
end
local Connection
local Thread = coroutine.wrap(function()
Connection = MyDataStore:OnUpdate("Cash"..player.UserId, function(Input)
UpdateGui(player);
Connection:Disconnect();
end);
end)
Thread();
end
local function OnPlayerRemoving(player)
local success, errormessage = pcall(function()
--MyDataStore:SetAsync("Cash"..player.UserId, player.leaderstats.Cash.Value);
MyDataStore:UpdateAsync("Cash"..player.UserId,function(OldValue)
local DataInDataStore
local success, errormessage = pcall(function()
DataInDataStore = MyDataStore:GetAsync("Cash"..player.UserId);
end)
if success then
if DataInDataStore ~= nil then
local NewValue = OldValue or 0
NewValue = NewValue
return NewValue
else
return nil
end
else
warn(errormessage);
end
end);
end)
if success then
print("Data successfully saved");
else
warn(errormessage);
end
end
--Events
Players.PlayerAdded:Connect(OnPlayerAdded);
Players.PlayerRemoving:Connect(OnPlayerRemoving);
Btw just a side note:
sometimes i get this error: 11:20:57.632 - DataStore request was added to queue. If request queue fills, further requests will be dropped. Try sending fewer requests.Key = Cash1106085551
idk why it happenes it doesn’t show the source and It doesn’t happens everytime.
As there are no wait()s in the above function, its calling :GetAsync() twice at the exact same time. I believe you have to wait around 6 seconds between :GetAsync()s but don’t take my word for it.
you can save the data once the player leaves with game.Players.PlayerRemoving:Connect() and also when the server shuts down, with game:BindToClose(function() you need to use these both for a proper result