hello!! i want to make an animation Textbutton where, if you click a button, your character will do an animation, but once its clicked again, the character will stop doing the animation and go back to their idle pose.
Everything works, but for some reason, when you click the button to stop the animation, it doesn't stop it. In this case, I want my character to sleep when I click the button. But when I click the button again to make him stop sleeping, he just keeps doing the sleeping animation. He can get up if you jump, but his idle animation seems to be stuck overlapping with the sleeping animation from that point onward.
local player = game.Players.LocalPlayer local humanoid = player.Character:WaitForChild('Humanoid') On = false local sleepanim = Instance.new("Animation") sleepanim.AnimationId = "rbxassetid://2794620010" script.Parent.MouseButton1Click:connect(function() if On == false then local playAnim = humanoid:LoadAnimation(sleepanim) playAnim:Play() humanoid.WalkSpeed = 0 On = true elseif On == true then local playAnim = humanoid:LoadAnimation(sleepanim) playAnim:Stop() humanoid.WalkSpeed = 16 On = false end end)
Does anyone know why this is happening? thank you!! (I dont know if this is relevant to the problem, but the animation's priority is "core" and its looped.)
The reason this is happening is that you are loading a new instance of the animation on line 12 and then stopping the animation track you just created. Because this is not the animation track that you started playing on line 13, stopping it will not do anything.
You will either need to store the original animation track in a global variable, or use Humanoid:GetPlayingAnimationTracks() to iterate through all playing animation tracks and stop the sleep animation.
Use of global variable:
local player = game.Players.LocalPlayer local humanoid = player.Character:WaitForChild('Humanoid') On = false local CurrentTrack; local sleepanim = Instance.new("Animation") sleepanim.AnimationId = "rbxassetid://2727217171" script.Parent.MouseButton1Click:connect(function() if On == false then CurrentTrack = humanoid:LoadAnimation(sleepanim) CurrentTrack:Play() humanoid.WalkSpeed = 0 On = true elseif On == true and CurrentTrack then CurrentTrack:Stop() humanoid.WalkSpeed = 16 On = false end end)
Use of method Humanoid:GetPlayingAniamtionTracks()
local player = game.Players.LocalPlayer local humanoid = player.Character:WaitForChild('Humanoid') On = false local sleepanim = Instance.new("Animation") sleepanim.AnimationId = "rbxassetid://2727217171" script.Parent.MouseButton1Click:connect(function() if On == false then local playAnim = humanoid:LoadAnimation(sleepanim) playAnim:Play() humanoid.WalkSpeed = 0 On = true elseif On == true then local PlayingTracks = humanoid:GetPlayingAnimationTracks(); for _, Track in ipairs (PlayingTracks) do if Track.Animation == sleepanim then Track:Stop(); end end humanoid.WalkSpeed = 16 On = false end end)