Why is my Script Erroing?

For some reason, I keep getting this error were I can’t load a animation.

  12:25:17.149  Unable to cast value to Object  -  Client - Animate:5
  12:25:17.149  Stack Begin  -  Studio
  12:25:17.149  Script 'Workspace.NubblyFry.Animate', Line 5  -  Studio - Animate:5
  12:25:17.149  Stack End  -  Studio

Here is the Script:

local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")

local idleAnim = "rbxassetid://7208722455"
local idleAnimTrack = humanoid.Animator:LoadAnimation(idleAnim)

local runAnim = "rbxassetid://7208894477"
local runAnimTrack = humanoid.Animator:LoadAnimation(runAnim)

humanoid.Running:Connect(function(speed)
	if speed == 0 then
		idleAnimTrack:Play()
	else
		if speed > 0 then
			runAnimTrack:Play()
		else
			runAnimTrack:Stop()
		end
	end
end)

initialize animations like this instead:

local idleAnim = Instance.new("Animation")
idleAnim.AnimationId = "whatever"

That’s not how LoadAnimation works. You have to make a an animation object. The correct way would be:

local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")

local idleAnim = Instance.new("Animation")
idleAnim.AnimationId = "rbxassetid://7208722455"
local idleAnimTrack = humanoid.Animator:LoadAnimation(idleAnim)

local runAnim = Instance.new("Animation")
runAnim.AnimationId = "rbxassetid://7208894477"
local runAnimTrack = humanoid.Animator:LoadAnimation(runAnim)

humanoid.Running:Connect(function(speed)
	if speed == 0 then
		idleAnimTrack:Play()
	else
		if speed > 0 then
			runAnimTrack:Play()
		else
			runAnimTrack:Stop()
		end
	end
end)
1 Like

I prefer this, as humanoid.Running never works for me, try this, its better

humanoid.StateChanged:Connect(function(old,new)
  if new == Enum.HumanoidStateType.Running then
    local speed = humanoid.WalkSpeed
	if speed == 0 then
		idleAnimTrack:Play()
	else
		if speed > 0 then
			runAnimTrack:Play()
		else
			runAnimTrack:Stop()
		end
        end
   end
end)

Please don’t just throw scripts at people without giving them an explanation.

I understand other peoples scripts because I already have knowledge in it.

Here I added comments to @Deadwoodx’s script

humanoid.StateChanged:Connect(function(old,new) -- checks if humanoid state is changed
  if new == Enum.HumanoidStateType.Running then -- checks if the humanoid state is running
    local speed = humanoid.WalkSpeed 
	if speed == 0 then -- if walkspeed is zero play idle
		idleAnimTrack:Play()
	else
		if speed > 0 then -- but if it isnt do the run animation
			runAnimTrack:Play()
		else 
			runAnimTrack:Stop() -- when speed isnt over 0 anymore then stop the animation
		end
        end
   end

you need to make the animation script like this:
local Anim = Instance.new(“Animation”)
Anim.Parent = script.Parent
Anim.AnimationId = “rbxassetid://ANIMATIONID”
local AnimPlayer = script.Parent.Humanoid.Animator:LoadAnimation(Anim)
AnimPlayer:Play()