How to test if ontouch event was fired for a second time between a period of time?

I have a detection script and I want to make the NPC have different stats but with my code the first time it goes into a suspicious mode and walk to your current position and walks back but in a period of time it detects you again then it will go into chasing mode how will I do this?

Code:

hmm = 0
De = true
What = false
local hum = script.Parent.Guard.Humanoid
local GN = script.Parent.Guard
local Ac = GN.Head.Ac.A -- billboard gui
loop = false





script.Parent.Guard.DET.Touched:Connect(function(hit)
if De == true then -- debugging
	


if hit.Parent.Name == "Gun" then -- Gun your holding(It is auto equiped)
	De = false
script.Parent.Value.Value = false -- telling walking around point script to stop
hum:LoadAnimation(hum.Parent.Walk):Stop()	
hum:LoadAnimation(hum.Parent.What):Play()
hum.WalkSpeed = 0 -- stands still for a second
wait(2)
hum.WalkSpeed = 16 
hum:LoadAnimation(hum.Parent.Walk):Play()	
hum:LoadAnimation(hum.Parent.What):Stop()
hum:MoveTo(hit.Position) -- walks to you latest position
Ac.TextColor3 = Color3.fromRGB(231, 255, 14)
Ac.Text = "?"
hmm = hmm + 1
loop = true
wait(3)
script.Parent.Guard.DET.Touched:Connect(function() -- I want this to run when if your still in his detection box
if loop == true then
--if hmm == 2 then
	Ac.TextColor3 = Color3.fromRGB(255, 0, 4)
	Ac.Text = "!"
	hum.WalkSpeed = 30
	hum:LoadAnimation(hum.Parent.Walk):Stop()
	hum:LoadAnimation(hum.Parent.OHNO):Play()
	while true do
		wait(.5)
		local newpos = hit.Position
		hum:MoveTo(newpos)
		
		
		--end
		
	end
	end
end)
	
end
loop = false
Ac.Text = " "
script.Parent.Value.Value = true -- goes back to normal
De = true
hmm = 0
  
end
end)
1 Like

I didn’t read the script yet but I think it’s really annoying that your variables are either named random sounds like “hmm” and “what” or acronyms. You should probably name them better, so it won’t be confusing reading it over.

To do this, I would have a value representing the NPCs current state. On touch, check if the state is Idle or Suspicious. If it’s idle, set it to suspicious, if it’s suspicious change it to chase. When setting it to suspicious have it wait x seconds and check if it is still suspicious and not chase, if so then change it back to idle.

1 Like

Thanks so much I didn’t really know how to make the different states!