My datastore script is not saving any data and it is giving this error: ServerScriptService.Leaderstats:22: attempt to index nil with number
Here is my script:
local dataStoreService = game:GetService("DataStoreService")
local dataStore = dataStoreService:GetDataStore("SaveData")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local cash = Instance.new("IntValue")
cash.Name = "Cash"
cash.Parent = leaderstats
local exp = Instance.new("IntValue")
exp.Name = "Exp"
exp.Parent = leaderstats
local data
local success, errorMessage = pcall(function()
data = dataStore:GetAsync(player.UserId)
end)
if success then
cash.Value = data[0]
exp.Value = data[1]
else
print("Player has no data")
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local dataToSave = {
player.leaderstats.Cash.Value,
player.leaderstats.Exp.Value
}
local success, errorMessage = pcall(function()
dataStore:SetAsync(player.UserId, dataToSave)
end)
if success then
print("Data saved")
else
print("Data not saved")
warn(errorMessage)
end
end)