So, my aiming animation for the gun keeps playing after I release RightMouse, specifically if I have fired while aiming. This is the code. The script is in a LocalScript placed inside of a Tool and anim2 (aiming animation) is not looped.
UIS.InputBegan:Connect(function(input, gameprocessed)
track2 = nil
if input.UserInputType == Enum.UserInputType.MouseButton2 then
track2 = script.Parent.Parent.Humanoid.Animator:LoadAnimation(anim2)
track2:Stop()
track2:Play()
workspace.CurrentCamera.FieldOfView = 45
end
UIS.InputEnded:Connect(function(input, gameprocessed)
if input.UserInputType == Enum.UserInputType.MouseButton2 and track2 then
track2:Stop()
workspace.CurrentCamera.FieldOfView = 70
end
end)
end)
I tried to cleanup a few things, try and see if this works.
local track2
UIS.InputBegan:Connect(function(input, gameprocessed)
if input.UserInputType == Enum.UserInputType.MouseButton2 then
track2 = script.Parent.Parent.Humanoid.Animator:LoadAnimation(anim2)
track2:Stop()
track2:Play()
workspace.CurrentCamera.FieldOfView = 45
end
end)
UIS.InputEnded:Connect(function(input, gameprocessed)
if input.UserInputType == Enum.UserInputType.MouseButton2 and track2 then
track2:Stop()
workspace.CurrentCamera.FieldOfView = 70
end
end)
You shouldn’t put a connection inside another connection without disconnecting it. Otherwise, each time the connection fires, a new connection is created and never removed.
Here is some fixed up code:
UIS.InputBegan:Connect(function(input, gameprocessed)
-- If the correct button
if input.UserInputType == Enum.UserInputType.MouseButton2 then
-- Start the animation
local track2 = script.Parent.Parent.Humanoid.Animator:LoadAnimation(anim2)
track2:Play()
workspace.CurrentCamera.FieldOfView = 45
-- End the animation when the button is released
local connection
connection = UIS.InputEnded:Connect(function(input, gameprocessed)
if input.UserInputType == Enum.UserInputType.MouseButton2 then
connection:Disconnect() -- Remove the connection
track2:Stop() -- Stop the animation
workspace.CurrentCamera.FieldOfView = 70 -- Reset the FoV
end
end)
end
end)