Here's my datastore meant to save levels and skillpoints for my game, but it doesn't save. What's wrong with it?
local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("PlayerData")
local function onPlayerJoin(player)
local leaderstats = Instance.new('Folder')
leaderstats.Name = 'leaderstats'
leaderstats.Parent = player
local Level = Instance.new('IntValue')
Level.Name = 'Level'
Level.Parent = leaderstats
local Exp = Instance.new('IntValue')
Exp.Name = 'Exp'
Exp.Parent = leaderstats
local HP = Instance.new('IntValue')
HP.Name = 'Hp'
HP.Parent = leaderstats
local ST = Instance.new('IntValue')
ST.Name = 'StrengthPoints'
ST.Parent = leaderstats
local DP = Instance.new('IntValue')
DP.Name = 'DodgePoints'
DP.Parent = leaderstats
local SkillPoints = Instance.new('IntValue')
SkillPoints.Name = 'SkillPoints'
SkillPoints.Parent = leaderstats
local playerUserId = 'Player_'..player.UserId
local data = playerData:GetAsync(playerUserId)
if data then
SkillPoints.Value = data["SkillPoints"]
DP.Value = data["DodgePoints"]
ST.Value = data["StrengthPoints"]
HP.Value = data["Hp"]
Exp.Value = data["Exp"]
Level.Value = data["Level"]
else
SkillPoints.Value = 0
DP.Value = 0
ST.Value = 0
HP.Value = 0
Exp.Value = 0
Level.Value = 1
if Level.Value == 0 then
Level.Value = 1
end
end
end
local function create_table(player)
local player_stats = {}
for _, stat in pairs(player.leaderstats:GetChildren()) do
player_stats[stat.Name] = stat.Value
end
return player_stats
end
local function onPlayerExit(player)
local player_stats = create_table(player)
local success, err = pcall(function()
local playerUserId = 'Player_'..player.UserId
playerData:SetAsync(playerUserId, player_stats)
end)
if not success then
warn('Couldnt save data')
end
end
game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerExit)
