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

How can I could detect if a player is there and if not then cancel the action?

So basically I need to do the action and if no player is detected then cancel it because if you click then touch them after like 100 seconds then it still does damage even though there is no player here is script:

Normal:

local A = script.Parent:WaitForChild("Attack")
local Tool = script.Parent
local B = script.Parent.Blade

local Damage = 10
local Debounce = false
local Cooldown = 2

A.OnServerEvent:Connect(function(player)
	B.Touched:Connect(function(hit)
		if(hit.Parent.Name ~= player.Name)then
			if(Debounce == false)then
				Debounce = true
				local H = hit.Parent:WaitForChild("Humanoid")
				H:TakeDamage(Damage)
				wait(Cooldown)
				Debounce = false
			end
		end
	end)
end)

Local:

local Tool = script.Parent
local Debounce = false
local Cooldown = 2

local A = script.Parent:WaitForChild("Attack")
local Stab = script:WaitForChild("Stab")

local P = game.Players.LocalPlayer
local H = P.Character:WaitForChild("Humanoid")
local Anim = H:LoadAnimation(Stab)

Tool.Activated:Connect(function()
	if(Debounce == false)then
		Debounce = true
		Anim:Play()
		A:FireServer()
		wait(Cooldown)
		Debounce = false
	end
end)

1 answer

✓ Accepted answer

If you want to stop the Touched event from firing, you must disconnect the event. I’m not sure what you mean by cancel if no player is detected, but disconnecting will still be used. One thing to remember while disconnecting is that to disconnect an event from itself, the variable for the connection must be initiated before adding the connection to it.

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