Hello.
I am creating a push tool, that ragdolls the a player whenever they get near the other player when they are clicking.
However, whenever the player stops clicking, the function continues looping. I can’t figure out a way to stop it. I tried using :
if script.parent.Deactivated then return end
This does not work. I’m not sure if I’m placing it in the wrong spot (I tried other places as well), but here is my full code.
local debounce = false
script.parent.Activated:Connect(function()
script.Parent.Handle.Touched:Connect(function(hit)
if debounce then return end
debounce = true
print("Part was touched")
if hit.Parent:FindFirstChild("Humanoid") then
hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health
hit.Parent.Humanoid:ChangeState(Enum.HumanoidStateType.FallingDown)
script.parent.Punch:Play()
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
game.ReplicatedStorage.RemoteEvent:FireClient(player)
end
end
wait(0.25)
debounce = false
end)
if script.parent.Deactivated then return end
end)
Like I said before, the script works fine, with the function activating when the tool is activated, but I can’t stop it whenever the player stops clicking.
script.parent.Deactivated is an event not a function, it detects if the player released left mouse button after pressing it
Also an event will keep checking and firing functions unless you disconnect it
You can try make an event connection in .Activated and then remove that connection in .Deactivated, like this
local debounce = false
script.parent.Activated:Connect(function()
event_connection = script.Parent.Handle.Touched:Connect(function(hit)
if debounce then return end
debounce = true
print("Part was touched")
if hit.Parent:FindFirstChild("Humanoid") then
hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health
hit.Parent.Humanoid:ChangeState(Enum.HumanoidStateType.FallingDown)
script.parent.Punch:Play()
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
game.ReplicatedStorage.RemoteEvent:FireClient(player)
end
end
wait(0.25)
debounce = false
end)
end)
script.Parent.Deactivated:Connect(function()
event_connection:Disconnect()
end)
You are connecting a touch connection every time the player clicks. Those touch connections are never being disconnected (even if you stop clicking) and will still fire whenever the part is touched.
A simple solution is to move the touch connection outside the mouse connection. Create a bool value like ''local CanPush = false". Whenever the player clicks just change that value from false to true and then back to false after a certain duration. In your touch connection, have an if statement that checks if CanPush is true.
Never have a connection within a connection if you aren’t going to disconnect it. It will just lead to massive memory leaks really fast.