I’m trying to make it so the game saves the player’s walkspeed and jumppower after they leave the game or die with a datastore.
I think the datastore is being set up fine but it won’t update/save the player’s stats when they die or leave.
I have two scripts, both in the server script service. The first one sets up the datastore and the second one sets updates the player’s stats to the ones saved in the datastore
First script:
local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("ExtraData")
local function onPlayerJoin(player) -- Runs when players join
local leaderstats = Instance.new("Folder") --Sets up leaderstats folder
leaderstats.Name = "extrastats"
leaderstats.Parent = player
local speed = Instance.new("IntValue") --Sets up value for leaderstats
speed.Name = "Speed"
speed.Parent = leaderstats
local jump = Instance.new("IntValue") --Sets up value for leaderstats
jump.Name = "Jump"
jump.Parent = leaderstats
local level = Instance.new("IntValue") --Sets up value for leaderstats
level.Name = "idk"
level.Parent = leaderstats
local playerUserId = "Player_" .. player.UserId --Gets player ID
local edata = playerData:GetAsync(playerUserId) --Checks if player has stored data
if edata then
speed.Value = edata['Speed']
jump.Value = edata['Jump']
level.Value = edata['idk']
else
-- Data store is working, but no current data for this player, (starting value)
speed.Value = 20
jump.Value = 30
level.Value = 0
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) --Runs when players exit
local player_stats = create_table(player)
local success, err = pcall(function()
local playerUserId = "Player_" .. player.UserId
playerData:SetAsync(playerUserId, player_stats) --Saves player data
end)
if not success then
warn('Could not save data!')
end
end
game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerExit)
Second script:
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(Player)
local jump = Player:WaitForChild("extrastats").Jump
local speed = Player:WaitForChild("extrastats").Speed
Player.CharacterAdded:Connect(function(Character)
local Humanoid = Character:FindFirstChild("Humanoid")
speed.Value = Humanoid.WalkSpeed
jump.Value = Humanoid.JumpPower
end)
end)
I have tried looking for answers on google and here but I’ve just gotten a bit stuck and would appreciate any help, thanks!
.