This script doesn’t seem right. What am I missing? There is no actual errors that I can see but it took a couple of tries to get the loadPlayerData to print so I think I’m missing or have overlooked something.
-- Load the DataStoreService
local DataStoreService = game:GetService("DataStoreService")
local playerDataStore = DataStoreService:GetDataStore("PlayerData_02")
local runService = game:GetService("RunService")
-- Function to load player data from the data store
local function loadPlayerData(player)
local success, data = pcall(function()
return playerDataStore:GetAsync(player.UserId)
end)
if success and data then
local leaderstats = player:WaitForChild("leaderstats")
leaderstats.Strength.Value = data.Strength or 0
leaderstats.Speed.Value = data.Speed or 0
leaderstats.Vitality.Value = data.Vitality or 0
leaderstats.JumpPower.Value = data.JumpPower or 0
print("Successfully loaded player data: ", player.Name)
else
print("Unable to load player data, try again later")
player:Kick()
end
end
-- Function to save player data to the data store
local function savePlayerData(player)
local leaderstats = player:WaitForChild("leaderstats")
local dataToSave = {
Strength = leaderstats.Strength.Value,
Speed = leaderstats.Speed.Value,
Vitality = leaderstats.Vitality.Value,
JumpPower = leaderstats.JumpPower.Value,
}
local success, errorMessage = pcall(function()
playerDataStore:SetAsync(player.UserId, dataToSave)
end)
if not success then
warn("Failed to save player data for "..player.Name..": "..errorMessage)
else
print("Successfully saved player data: ", player.Name)
end
end
-- Connect the PlayerAdded event
game.Players.PlayerAdded:Connect(function(player)
-- Create the leaderstats folder for the player
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
-- Create the IntValues for the player's stats
local strength = Instance.new("IntValue")
strength.Name = "Strength"
strength.Value = 0
strength.Parent = leaderstats
local speed = Instance.new("IntValue")
speed.Name = "Speed"
speed.Value = 0
speed.Parent = leaderstats
local vitality = Instance.new("IntValue")
vitality.Name = "Vitality"
vitality.Value = 0
vitality.Parent = leaderstats
local jumpPower = Instance.new("IntValue")
jumpPower.Name = "JumpPower"
jumpPower.Value = 0
jumpPower.Parent = leaderstats
-- Load the player's data from the data store
loadPlayerData(player)
end)
-- Save the player's data to the data store when they leave the game
game.Players.PlayerRemoving:Connect(function(player)
savePlayerData(player)
end)
-- Save all player data when the server shuts down
game:BindToClose(function()
print("Server shutting down")
-- Check if we're in Studio
if runService:IsStudio() then
return
end
for _, player in ipairs(game.Players:GetPlayers()) do
task.spawn(function()
savePlayerData(player)
end)
end
end)