I’ve been attempting a part that plays an animation while touching it and stopping it when you stop touching it.
Here is what I have so far. It is not in a local script. I believe that is worth noting.
local a = true
function onTouched(hit)
if a == true then
local human = hit.Parent:findFirstChild("Humanoid")
local prone = script.Parent.Animation
local animloader = human:LoadAnimation(prone)
if human then
animloader:Play()
a = false
end
end
end
script.Parent.Touched:connect(onTouched)
script.Parent.Parent.e.TouchEnded:Connect(function(hit)
local human = hit.Parent:findFirstChild("Humanoid")
local prone = script.Parent.Animation
local animloader = human:LoadAnimation(prone)
if human then
animloader:Stop()
a = true
end
end)
I’ve tried everything I can find and I still cant find a fix. What happens is the player starts the animation but when leaving it doesn’t stop. Also sometimes to animation randomly restarts presumably due to a touched issue.
Your order is wrong, the human variable within your onTouched function has the POTENTIAL to return back as nil, since you’re calling a Humanoid function without checking to make sure human is valid
It’s also better to use FindFirstChildOfClass in this case, as you’re trying to search for a class object of the hit.Parent found
I also wouldn’t recommend using TouchEnded, as it can be really unreliable at certain times & come up more with an alternative instead, like GetPartBoundsInBox/GetPartBoundsInRadius, or Magnitude
local a = true
local prone = script.Parent.Animation
local Animation -- Instead of creating individual animations for each Event, store this as a local variable outside the function scopes
function onTouched(hit)
local Target = hit.Parent
if not a or not Target then
return
end
local human = Target:FindFirstChildOfClass("Humanoid")
if not human then
return
end
local Animator = human:FindFirstChildOfClass("Animator")
if Animator ~= nil then
a = false
Animation = Animator:LoadAnimation(prone)
Animation:Play()
end
end
script.Parent.Touched:connect(onTouched)
-- I seriously recommend using something else, but I'll leave this here so that your code can work
script.Parent.Parent.e.TouchEnded:Connect(function(hit)
local Target = hit.Parent
if a or not Target then
return
end
local human = Target:FindFirstChildOfClass("Humanoid")
if not human or Animation == nil then
return
end
Animation:Stop()
a = true
end)