I'm trying to make a script for when I hold the X key, the animation starts, and when I release, it stops. Well, everything was going well, until I tested it. I get the error, "Unable to cast value to Object" This happens on line 5 of my code. The code is below:
local player = game.Players.LocalPlayer local human = player.Character:WaitForChild("Humanoid") local animation = Instance.new("Animation") local ca = "rbxassetid://2401982156" local canimation = human:LoadAnimation(ca) game:GetService("UserInputService").InputBegan:Connect(function(input,gameprocesed) if input.KeyCode == Enum.KeyCode.X then canimation:Play() end end) game:GetService("UserInputService").InputEnded:Connect(function(input,gameprocesed) if input.KeyCode == Enum.KeyCode.X and canimation.IsPlaying then canimation:Stop() end end)
Can someone please help me?
You didnt paste animation id into Animation what you created, so try this. Just insert LocalScript in StarterGui or StarterPack then copy, paste this code into that localscript.
wait() local player = game:GetService("Players").LocalPlayer local char = player.Character or player.CharacterAdded:Wait() local human = char:WaitForChild("Humanoid") local AnimVar= Instance.new("Animation") AnimVar.AnimationId = "rbxassetid://2400830112" local AnimTrack = human:LoadAnimation(AnimVar) game:GetService("UserInputService").InputBegan:Connect(function(input,gameprocesed) if input.KeyCode == Enum.KeyCode.X then AnimTrack:Play() end end) game:GetService("UserInputService").InputEnded:Connect(function(input,gameprocesed) if input.KeyCode == Enum.KeyCode.X then AnimTrack:Stop() end end)
i just realised what you were doing wrong, its that you didnt set the parent of the Animation
so it wont work, also i think your only suppose to use the ID of the animation if your not using the Instance Animation
.
local player = game.Players.LocalPlayer local human = player.Character:WaitForChild("Humanoid") local animation = Instance.new("Animation") local ca = "2401982156" local canimation = human:LoadAnimation(ca) animation.Parent = workspace -- define where you want the animation to be a child of game:GetService("UserInputService").InputBegan:Connect(function(input,gameprocesed) if input.KeyCode == Enum.KeyCode.X then canimation:Play() end end) game:GetService("UserInputService").InputEnded:Connect(function(input,gameprocesed) if input.KeyCode == Enum.KeyCode.X and canimation.IsPlaying then canimation:Stop() end end)