How do I use Humanoid.StateChanged?

Hello. I’ve been searching how to use Humanoid.StateChanged but I couldn’t find any examples of how to use it, and my attempts on using it have failed. I want to use this function to detect if a player started climbing, jumping, or if the player landed.
I tried using it in two ways:

humanoid.StateChanged:Connect(function()
	if humanoid.StateChanged == Enum.HumanoidStateType.Climbing then
		if humanoid.GetState(Enum.HumanoidStateType.Climbing) == true then
			print("climbing")
		end
	end
end)
humanoid.StateChanged:Connect(function(climbing)
	if climbing == Enum.HumanoidStateType.Climbing then
		if climbing == true then
			print("climbing")
		end
	end
end)

Neither worked. I would like to know how to use it correctly. Thanks in advance.

Edit 1: I found a few examples in the documentation for the Humanoid, but I don’t understand how it works.

Humanoid.StateChanged

local function onStateChanged(_oldState, newState) -- here, two arguments
	if newState == Enum.HumanoidStateType.Climbing then -- check newState
		print("climbing")
	end
end

humanoid.StateChanged:Connect(onStateChanged)

first, the function receives two arguments. the _oldState and the newState.
you are most likely interested in the newState, so you need both arguments.

Humanoid:GetState()
second, of course you can also just use humanoid:GetState() to retrieve the current state. notice we use colon : for the call.

local function onStateChanged()
	local newState = humanoid:GetState()
	if newState  == Enum.HumanoidStateType.Climbing then
		print("climbing")
	end
end

humanoid.StateChanged:Connect(onStateChanged)

if you understand these, try to check and compare with the examples in the documents for better understanding of syntax

1 Like

Thank you. It makes sense to me now. The “StateChanged” function is most relevant for what I would like to do right now.

1 Like