why is my DataStore script not working even tho it seems like it doesn’t have errors:
-- Variables
local DataStoreService = game:GetService("DataStoreService")
local DataStore1 = DataStoreService:GetDataStore("DataStore1")
-- Classic Leaderstats script lines 5-15
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local Cash = Instance.new("IntValue", leaderstats)
Cash.Name = "Cash"
Cash.Value = 1
-- DataStore Script lines 19-48
local playerUserId = "Player_"..player.UserId
local data
local success, errormessage = pcall(function()
data = DataStore1:GetAsync(playerUserId) --Load Data
end)
if success then
Cash.Value = data.Cash -- Set Player Data equal to currency in the game
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local playerUserId = "Player_"..player.UserId
local data = {Cash = player.leaderstats.Cash.Value}
local success, errormessage = pcall(function()
DataStore1:SetAsync(playerUserId, data)
end)
if success then
print("Data Saved!")
else
print("There was an error while saving data")
warn(errormessage)
end
end)
I learned datastores a couple days ago and I had trouble with them too. I know you need to have the API enabled, just do as follows
Then go to options and turn on the studio API services.
I tried the script and gave me error
(ServerScriptService.Script:23: attempt to index nil with ‘Cash’)
So that mean if a new player joined without data. It won’t know what is data((.Cash))
to fix that just add
if success then
if data ~= nil then
Cash.Value = data.Cash
end
end