Saving WalkSpeed on death

I have been trying to make a script that saves the players speed on death and then giving them the speed after respawning, but it does not work and it shows no errors in the output. Hopefully i can get another set of eyes on this.

Heres the code:

game.Players.PlayerAdded:Connect(function(plr)

	local jumpValue = plr:WaitForChild("Values").JumpPower
	local speedValue = plr:WaitForChild("Values").WalkSpeed
	while true do
		local char = plr.CharacterAdded:Wait()
		local hum = char:WaitForChild("Humanoid")

		if hum.Health == 0 then
			speedValue.Value = hum.WalkSpeed
			jumpValue.Value = hum.JumpPower

			repeat wait(0.1) until hum == nil
			wait(0.5)
			hum.JumpPower = jumpValue.Value
			hum.WalkSpeed = speedValue.Value-

		end
	end
end)

It’s probably because you are firing the function once the player is dead and once they respawn it doesn’t save because you were firing the function for the dead player. I could be wrong though.

1 Like

Little comment on the while loop.
Why not use events instead :stuck_out_tongue:

plr.CharacterAdded:Connect(function(char)
   local hum = char:WaitForChild("Humanoid")
   hum.Died:Connect(function()
      print(plr.." died")
    end)
end)

The way you have the code doesn’t rely on the builtin events for the character. Instead of doing all that, you could try


	local jumpValue = plr:WaitForChild("Values").JumpPower
	local speedValue = plr:WaitForChild("Values").WalkSpeed
	plr.CharacterAppearanceLoaded:Connect(function(char)
		local hum = char:WaitForChild("Humanoid")

        hum.JumpPower = jumpValue.Value
		hum.WalkSpeed = speedValue.Value

        hum.Died:Connect(function()
            speedValue.Value = hum.WalkSpeed
			jumpValue.Value = hum.JumpPower
        end)
	end)

This code is bascially how you did it but using events that run when something specific happens. How this works is it waits for the character to fully load before running the CharacterAppearanceLoaded event, which sets the Jump Height and WalkSpeed, and then sets an event for when the player dies to store the WalkSpeed and the JumpPower

Why are you using a WaitForChild when you already waited in the above line? Seems like it’s just taking up more space.

try using characterAdded rather then using while true do loop, The CharacterAdded event fires when a player’s character spawns (or respawns)

local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(Player)
	local jumpValue = Player:WaitForChild("Values").JumpPower
	local speedValue = Player:WaitForChild("Values").WalkSpeed
	
	Player.CharacterAdded:Connect(function(Character)

		local Humanoid = Character:FindFirstChildWhichIsA("Humanoid")
		speedValue.Value = Humanoid.WalkSpeed
		jumpValue.Value = Humanoid.JumpPower

	end)
end)
1 Like