Can't get humanoid?

For whatever reason, Roblox just can’t get the humanoid! Why?! No idea!

Here is my script, I get the error the line:
trackAnimation = plr.Character.Humanoid.Animator:LoadAnimation(animation) and I have no idea why, because the game.Players.LocalPlayer.Character does consist of a Humanoid. (See full script for better context below)’

Full script:

-- Plays animation when button clicked

local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://7492057564"

local trackAnimation = nil
local playability = true

local plr = game.Players.LocalPlayer

function PlayAnimation(animationSource)
	if playability == true then
		trackAnimation = plr.Character.Humanoid.Animator:LoadAnimation(animation)
		trackAnimation.KeyframeReached:Connect(function()
		end)
		trackAnimation:Play()
		playability = false
		wait(math.random(1,4))
		playability = true
	end
end

while true do
	PlayAnimation()
end

Funny because if you connect the function to a MouseButton1Click event instead of a loop, it works perfectly, plays when you need too, and most importantly doesn’t give you a message in the output.

The error is the Humanoid is not a valid member of my Workspace.(MyUsername) but when you open the character, it is there.

1 Like

The humanoid needs time to load in.

Replace .Humanoid with :WaitForChild(“Humanoid”)

2 Likes

So like this?

trackAnimation = plr.Character:WaitForChild("Humanoid").Animator:LoadAnimation(animation)
1 Like

Yes. Humanoid is usually last to load in I believe, you also should use CharaterAdded on plr to ensure the character exists and your not referencing nil.

Try this

-- Plays animation when button clicked

local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://7492057564"

local trackAnimation = nil
local playability = true

local plr = game.Players.LocalPlayer

function PlayAnimation(animationSource)
	if playability == true then
		local character = plr.Character or plr.CharacterAdded:Wait()
		local hum = character:WaitForChild("Humanoid")
		trackAnimation = hum:WaitForChild("Animator"):LoadAnimation(animation)
		trackAnimation.KeyframeReached:Connect(function()
		end)
		trackAnimation:Play()
		playability = false
		wait(math.random(1,4))
		playability = true
	end
end

while true do
	PlayAnimation()
end
1 Like

Remember if your issue has been solved to mark it as solved.
Tap / click “:white_check_mark: Solution” on the post that fixed the issue.

Also the characters does too. Try

local char = plr.CharacterAdded:Wait() or plr.Character
char:WaitForChild('Humanoid').Animator:LoadAnimation(anim)
1 Like

Yes, that’s good. I suggest the script above me.

just load the animation once
i think loading a lot makes the player lags
or try removing the track after the function

Is it a script or localscript?