Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I stop a looping animation when the player clicks?

So I have an animation inside a tool, which plays when you equip the tool and click it. It's a looping animation, and I want to make it so it stops when you click for a second time. Here's my current code:

Tool = script.parent
local player = game.Players.LocalPlayer
repeat wait() until player.Character ~= nil
local hum = player.Character:WaitForChild("Humanoid")

local animation = Tool.Animation
local AnimTrack = hum:LoadAnimation(animation)

Tool.Selected:connect(function(mouse)
	 mouse.Button1Down:connect(function()
		AnimTrack:Play()
	end)
end)

1 comment

0

Selected isn’t an event.

2 answers

You can make a value checking if it's on or off

it's better just to show you myself

Tool = script.parent
local player = game.Players.LocalPlayer
repeat wait() until player.Character ~= nil
local hum = player.Character:WaitForChild("Humanoid")

local animation = Tool.Animation
local AnimTrack = hum:LoadAnimation(animation)

local On = false -- On value (if tool is on)

Tool.Selected:connect(function(mouse)
     mouse.Button1Down:connect(function()
	if not On then -- Checking if it's not on
          AnimTrack:Play()
	  On = true -- turning value to true because it is on now
	else
	  AnimTrack:Stop()
	  On = false -- turning value to true because it's off now
	end
    end)
end)

2 comments

0

thank you so much :)

0

My pleasure. Remember to accept the answer as it helps both the asker and the answerer.

Add a toggle variable. This would allow it to be clicked to start and stop over again.

Tool = script.parent
local toggle = false -- add a variable to toggle
local player = game.Players.LocalPlayer
repeat wait() until player.Character ~= nil
local hum = player.Character:WaitForChild("Humanoid")

local animation = Tool.Animation
local AnimTrack = hum:LoadAnimation(animation)

Tool.Selected:connect(function(mouse)
	if toggle == false then -- checks for the state
     mouse.Button1Down:connect(function()
        AnimTrack:Play()
	toggle = true --changes the state
    end)
  end
	if toggle == true then --changes the state
	AnimTrack:Stop()
	toggle = false -- changes the state
end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.