I am trying to play a animation for a npc when a button is pressed, I am new to scripting and need help.
local anim = Instance.new("Animation") anim.AnimationId = "rbxassetid://PUT_ID_HERE" local controller = workspace.Dummy1.Humanoid controller:LoadAnimation(anim):Play() local hum = script.Parent:WaitForChild("Humanoid") local anim = hum:LoadAnimation(script:FindFirstChildOfClass("Animation")) anim.Looped = false if inputObject.KeyCode == Enum.KeyCode.E then Humanoid:LoadAnimation(anim):Play() print("Animation is playing") end
I am assuming this is either from a tutorial or a free model, let me explain how this works because instead of not understanding how it works, you know how it works so you know where and what to change. Also, instead of using free models, learn from them because its dangerous with malicious scripts.
Lets get started. Assuming you know what variables are (hopefully you do).
local anim = Instance.new("Animation") anim.AnimationId = "rbxassetid://PUT_ID_HERE" -- IMPORTANT
This makes an asset called an Animation. This can also be made in the Explorer just like you do with parts. Assuming you know what animations ids are, change the "PUT_ID_HERE" to the animation id you want. This makes it so the animation is set up to the actual animation and not just a blank one.
local controller = workspace.Dummy1.Humanoid controller:LoadAnimation(anim):Play()
This is just loading and playing the animation on a dummy in the workspace.
local hum = script.Parent:WaitForChild("Humanoid") local anim = hum:LoadAnimation(script:FindFirstChildOfClass("Animation")) anim.Looped = false
This is where the problem is caused, but not occurring yet. We'll get to this later. This is just making a variable to hold the Humanoid for a character, and loading an animation in side of the character using that humanoid. Then it makes the animation not looped when the animation is finished.
if inputObject.KeyCode == Enum.KeyCode.E then Humanoid:LoadAnimation(anim):Play() print("Animation is playing") end
And finally, why you are getting an error. This is because there is no such variable known as "inputObject" and instead of using the name of the humanoid variable, "hum", it uses a different variable name, "Humanoid". A fixed script would be:
local anim = Instance.new("Animation") anim.AnimationId = "rbxassetid://PUT_ID_HERE" local UserInputService = game:GetService("UserInputService") local hum = script.Parent:WaitForChild("Humanoid") local loadedanim = hum:LoadAnimation(anim) loadedanim.Looped = false local function onInputBegan(input, gameProcessed) if input.KeyCode == Enum.KeyCode.E then Humanoid:LoadAnimation(anim):Play() print("Animation is playing") end end UserInputService.InputBegan:Connect(onInputBegan)
If you need further explanation on the working script, please do ask me! Don't be afraid too to ask questions! Everyone needs to start at some point, and you wont progress if you don't ask.