Hey, so this current script that I have, always seems to be returning nil whilst getting the datastore data. Now, all the Data Key’s are the same, and it saves data, because once I’ve left the game and check the data store value, it says the correct amount, but when I join the game, it comes up with nil when using :GetAsyc() any help would be appreciated!
Module Script:
local currency = {}
local DEFAULT_CASH = 0
local DEFAULT_BANK = 0
local BANK_COOLDOWN = 5
local RETRY_COOLDOWN = 5
local INCOME = 25
local DataStoreService = game:GetService("DataStoreService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local DataStore = DataStoreService:GetDataStore("MainData")
local Event = Instance.new("RemoteEvent", ReplicatedStorage) Event.Name = "PaycheckPrompt"
function currency:Initialize(Player)
local Data = Instance.new("Folder",Player) Data.Name = "Data"
local Bank = Instance.new("NumberValue",Data) Bank.Name = "Bank"
local Cash = Instance.new("NumberValue",Data) Cash.Name = "Cash"
local PlayerData = currency:GetData(Player)
print(PlayerData)
if PlayerData then
Bank.Value = PlayerData.Bank
Cash.Value = PlayerData.Cash
else
Bank.Value = DEFAULT_BANK
Cash.Value = DEFAULT_CASH
end
while Player do
wait(BANK_COOLDOWN)
if Player ~= nil and Player:IsDescendantOf(game.Players) then
Bank.Value += INCOME
Event:FireClient(Player, INCOME)
end
end
end
function currency:SaveData(Player)
local UserId = Player.UserId
local PlayerData = Player:FindFirstChild("Data")
warn(PlayerData.Bank.Value, PlayerData.Cash.Value, UserId)
local S,E = pcall(function()
DataStore:SetAsync(Player.UserId,
{
Bank = PlayerData.Bank.Value,
Cash = PlayerData.Cash.Value,
}
)
end)
if S then
warn(Player.Name.."'s data saved successfully.")
else
warn(Player.Name.."'s data failed to save : "..E)
delay(RETRY_COOLDOWN, function()
self:SaveData(Player)
end)
end
end
function currency:GetData(Player)
local UserId = Player.UserId
warn(UserId)
local S,R = pcall(function()
DataStore:GetAsync(Player.UserId)
end)
if (S) then
warn(R)
return R
else
warn("Failed to receive "..Player.Name.."'s data.")
end
end
function currency:SaveAllData()
for _, player in pairs(game.Players:GetPlayers()) do
currency:SaveData()
end
end
return currency
Script:
local ServerScriptService = game:GetService("ServerScriptService")
local Handlers = ServerScriptService:WaitForChild("Handlers")
local DataHandler = require(Handlers:WaitForChild("DataHandler"))
game.Players.PlayerAdded:Connect(function(Player)
DataHandler:Initialize(Player)
end)
game.Players.PlayerRemoving:Connect(function(Player)
DataHandler:SaveData(Player)
end)
