So I'm making a game on roblox that is meant to play an animation when you touch a brick. It's about 8 seconds long, (idk if that helps) I've tried multiple things, but none work so far. Here is what I've made so far
function onTouched(hit)
function debounce(deb)
debounce(1)
local human = hit.Parent:findFirstChild("Humanoid")
if human then
local anim = human:LoadAnimation(script.Parent.Animation)
anim:Play()
debounce(0)
end
end
script.Parent.Touched:connect(onTouched)
Sorry for such a dumb question, but I need to out what problems I have with my script.
You start by storing whatever it is you need in variables. In this case, you need the part that gives the animation, the animation itself. If it's a local script, you can load the animation to the local player from the script itself.
Next, you create a touch connection with the part and check if the part that hit it is actually a character. If it is a character, then you check if the animation is already playing. If it's not the case, then you play the animation.
Here's how:
01 | -- Variables |
02 | local part = script.Parent |
03 | local animationToLoad = part:FindFirstChild( "Animation" ) |
04 | -- Services |
05 | local Players = game:GetService( "Players" ) |
06 | local localPlayer = Players.LocalPlayer |
07 | local localChar = localPlayer.Character |
08 | local localHum = localChar:FindFirstChild( "Humanoid" ) |
09 | -- Load the animation to the humanoid |
10 | local anim = localHum:LoadAnimation(animationToLoad) |
11 | local db = true |
12 |
13 | part.Touched:connect( function (hit) |
14 | -- Check if the part that hit it is a character |
15 | local char = hit.Parent |
Let me know how it goes and if anything!
please attempt to correctly indent your code so others can read it but if you are using an animationtrack you can use the didloop event to make sure the animation fully completed once
refer to https://developer.roblox.com/en-us/api-reference/event/AnimationTrack/DidLoop for more details
01 | local run = true |
02 | function onTouched(hit) |
03 | if run = = true then |
04 | run = false |
05 | local human = hit.Parent:findFirstChild( "Humanoid" ) |
06 | if human then |
07 | local anim = human:LoadAnimation(script.Parent.Animation) |
08 | anim:Play() |
09 | anim.DidLoop:Connect( function () run = true anim:Stop end ) |
10 | end |
11 | end |
12 | end |
13 | script.Parent.Touched:connect(onTouched) |