How to play an animation on a npc when a part is touched

How to play an animation on a npc when a part is touched?

2 Likes

You can use part.Touched, so that when the part is touched, an event fires. And you can use Animator:LoadAnimation for the NPC’s animation, for when the event is fired.

1 Like

Can you like show it to me in a script because im pretty new

Of course.

local Part = script.Parent -- Doesn't work if the script isn't in the part.
local NPC = script.Parent.Parent.NPC -- Doesn't work if the NPC isn't in the script's parent's parent.
local Animation = script.Parent.Parent.Animation -- Doesn't work if the animation isn't in the script's parent's parent.

Part.Touched:Connect(function(Hit)
  local Player = game:GetService("Players"):GetPlayerFromCharacter(Hit.Parent)
  -- Trying to see if a player touched our part.

  if Player then
    -- Here's a statement of where if the player DID touch it, the event runs.
    local Anim = NPC.Humanoid.Animator:LoadAnimation(Animation) -- Makes a variable for the animation loader.
    Anim:Play() -- Plays the animation
  end
end)

If you don’t know what parent/child means, I could explain that to you aswell.

1 Like

I know what it means lol but thanks

Ima put this as a normal script in the
npc

1 Like

Yes, I’m pretty sure load animation works with server scripts too which is good in this case.

Also be sure to change the Part, NPC and animation variables to your part, etc.

Ok yes I did that :grinning: :grinning:

1 Like

It should work then, although I didn’t add a debounce (cooldown/wait). How long is your animation? I’ll just make the script but with a cooldown.

In the output says

 Animator is not a valid member of Humanoid "Workspace.Dummy.Humanoid"

Im just using a normal roblox animation to test it
https://www.roblox.com/catalog/5104377791/Hero-Landing

Oh that means there’s no animator in the NPC, which is fine. I guess I’ll try it with the Humanoid, although that might not work cause roblox deprecated it.

local Part = script.Parent -- Doesn't work if the script isn't in the part.
local NPC = script.Parent.Parent.NPC -- Doesn't work if the NPC isn't in the script's parent's parent.
local Animation = script.Parent.Parent.Animation -- Doesn't work if the animation isn't in the script's parent's parent.
local Debounce = false

Part.Touched:Connect(function(Hit)
  local Player = game:GetService("Players"):GetPlayerFromCharacter(Hit.Parent)
  -- Trying to see if a player touched our part.

  if Player and Debounce == false then
    Debounce = true
    -- Here's a statement of where if the player DID touch it, the event runs.
    local Anim = NPC.Humanoid:LoadAnimation(Animation) -- Makes a variable for the animation loader.
    Anim:Play() -- Plays the animation
    wait(4) -- Wait 4
    Debounce = false
  end
end)
1 Like