script.Parent.Activated:Connect(function() local animation = script.Parent.Animation local animationtrack = game.Players.LocalPlayer.Character.Humanoid:LoadAnimation(animation) animationtrack:Play() script.Parent.Handle.Touched:Connect(function(Hit) if animationtrack.IsPlaying then Hit.Parent:FindFirstChild("Humanoid"):TakeDamage(5) else script.Parent.Handle.Touched:Disconnect() -- problem end end) end)
I am trying to disconnect the event, but it just gives me an error instead.
I feel bad for the amount of crap answer you have got. So this is A way to do it. Its what I use. We just create a bool variable and check it when the function is ran
disconnected = false script.Parent.Touched:Connect(function(touch) if disconnected then return end --We check to see if the function has been "Disconnected" --Code here end)
If you need to actually disconnect the event, do something like this:
-- "PartTouched" now represents what "connect()" returns, which is the event signal for this individual event. local PartTouched = Part.Touched:connect(function() print("Part touched") end) -- Once you have a reference to that signal, you can then disconnect it by calling the "disconnect()" method on it whenever you want. PartTouched:disconnect()
You can set the disconnected to true or false at your descretion/as needed. I hope I was able to help. If you have any questions, feel free to comment to my post.
since you have connected the function on the same line, it will not work
local Initiate = function() print("hi") end local connection = script.Parent.Touched:Connect(Initiate) wait(1) connection:Disconnect()
So you would do something like
local function TouchEvent(hit) if animationtrack.IsPlaying then hit.Parent:FindFirstChildOfClass("Humanoid"):TakeDamage(5) else connection:Disconnect() end end local connection = script.Parent.Handle.Touched:Connect(TouchEvent) --connects the event to the function
Like this:
script.Parent.Activated:Connect(function() local animation = script.Parent.Animation local animationtrack = game.Players.LocalPlayer.Character.Humanoid:LoadAnimation(animation) animationtrack:Play() local connection = script.Parent.Handle.Touched:Connect(function(Hit) if animationtrack.IsPlaying then local humanoid = Hit.Parent:FindFirstChild("Humanoid") if humanoid then -- added extra check here, otherwise your script may error when touched by a non humanoid humanoid:TakeDamage(5) end else connection:Disconnect() end end) end)
Edit:Consider adding debounce.