States Wont Update After Respawn

okay so i made this ragdoll script that ragdolls when the player is in the air for more than 0.7 seconds.
this only works before the player dies, if the player does die it doesnt work again. i tried to fix it in the script but that didnt work so i need someones help! if you can repair the code please reply!

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local deadly = false
local fallingEvent = game:GetService("ReplicatedStorage"):WaitForChild("FallingEvent")

local fallingStartTime = nil

local function onCharacterAdded()
	print("Player respawned")
	fallingStartTime = nil
	print("reset fallingtime")
	print(fallingStartTime)
end

player.CharacterAdded:Connect(onCharacterAdded)

humanoid.StateChanged:Connect(function(oldState, newState)
	if newState == Enum.HumanoidStateType.Freefall then
		fallingStartTime = tick()
	elseif oldState == Enum.HumanoidStateType.Freefall then
		local fallingDuration = tick() - fallingStartTime
		if fallingDuration > 0.7 then
			fallingEvent:FireServer()
		end
		fallingStartTime = nil
	end
end)

Where is the script located in the explorer?

its located in StarterPlayerScripts

Is this printing the first time and when the player respawns?

yes it is, thats the bit im confused on

Put all this code as well as the character and humanoid variables inside the onCharacterAdded function. StateChanged is being connected for the first time but when the player dies, it is disconnected and is not connected back since the player receives a new character and humanoid instance.

so you mean like this?

local function onCharacterAdded()
	humanoid.StateChanged:Connect(function(oldState, newState)
		fallingStartTime = nil
	end)
end

Here:

local player = game.Players.LocalPlayer
local deadly = false
local fallingEvent = game:GetService("ReplicatedStorage"):WaitForChild("FallingEvent")

local fallingStartTime = nil

local function onCharacterAdded()
	local character = player.Character or player.CharacterAdded:Wait()
	local humanoid = character:WaitForChild("Humanoid")
	
	fallingStartTime = nil
	humanoid.StateChanged:Connect(function(oldState, newState)
		if newState == Enum.HumanoidStateType.Freefall then
			fallingStartTime = tick()
		elseif oldState == Enum.HumanoidStateType.Freefall then
			local fallingDuration = tick() - fallingStartTime
			if fallingDuration > 0.7 then
				fallingEvent:FireServer()
			end
			fallingStartTime = nil
		end
	end)
	
	print("Player respawned")
	print("reset fallingtime")
	print(fallingStartTime)
end

player.CharacterAdded:Connect(onCharacterAdded)

thank you so much! that worked my brain was so fried ty

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.