Hello, i am trying to make a datastore which saves the player’s data, if there is no data, it will assign the default data, the default data says ["Kills"] = 5,
Issue: However, I have no data in the game and it doesn’t set my default data to 5 kills. It sets it to 0.
Please know that I am new to DataStore, and it is a real pain.
Please help me, too.
My DataSave script in ServerScriptSerivce:
local dataStoreservice = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local leaderstatsData = dataStoreservice:GetDataStore("data")
local sessionData = {}
function PlayerAdded(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
local Coins = Instance.new("IntValue")
Coins.Name = "Coins"
Coins.Parent = leaderstats
local kills = Instance.new("IntValue")
kills.Name = "Kills"
kills.Parent = leaderstats
local deaths = Instance.new("IntValue")
deaths.Name = "Deaths"
deaths.Parent = leaderstats
local success = nil
local playerData = nil
local attempt = 1
repeat
success, playerData = pcall(function()
return leaderstatsData:GetAsync(player.UserId)
end)
attempt += 1
if not success then
warn(playerData)
task.wait(3)
end
until success or attempt == 5
if success then
print("Connected to database")
if not playerData then
print("Assigning default data")
playerData = {
["Kills"] = 5,
["Deaths"] = 0,
["Coins"] = 0
}
end
sessionData[player.UserId] = playerData
else
warn("Unable to get data for", player.Name)
player:Kick("Unable to load your data. Try again later")
end
kills.Value = sessionData[player.UserId].Kills
kills.Changed:Connect(function()
sessionData[player.UserId].kills = kills.Value
end)
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(PlayerAdded)
function PlayerLeaving(player)
if sessionData[player.UserId] then
local success = nil
local errorMsg = nil
local attempt = 1
repeat
success, errorMsg = pcall(function()
leaderstatsData:SetAsync(player.UserId, sessionData[player.UserId])
end)
attempt += 1
if not success then
warn(errorMsg)
task.wait(3)
end
until success or attempt == 5
if success then
print("Data saved for", player.Name)
else
warn("Unable to save for", player.Name)
end
end
local playerData = {
Kills = player.leaderstats.Kills.Value,
Deaths = player.leaderstats.Deaths.Value,
Coins = player.leaderstats.Coins.Value
}
leaderstatsData:SetAsync(player.UserId, playerData)
end