TouchEnded isn't being executed when NPC is :Destroy(), what am I doing wrong?

Hello! I am currently making a FNAF fan game. I will go over my problem real quick.

In the camera system, there is a vent camera, which gives two maps of both floors and show the vents. Basically, the characters/npc move in game, so there are vent detectors. The vent detectors work well but…

How things work is sometimes, npcs will be :Clone() from ServerStorage to Workspace. The current npc will be :Destoy(). The problem is, if for example an npc in a vent gets :Destroy(), the vent detector will still think the npc is there and not run TouchEndend.

Is there anyways I can fix this. If there’s any confusion or lack of important details please tell me!

Script:

for x,Vent in pairs(VentsFolder:GetChildren()) do

function VentHit(hit)
	if (hit.Parent:FindFirstChild("Humanoid") ~= nil) then
		VentsMap[Vent.name].Visible = true
	end
end

Vent.Touched:Connect(VentHit)

end

for x,Ventend in pairs(VentsFolder:GetChildren()) do

function VentHit(hit)
	if (hit.Parent:FindFirstChild("Humanoid") ~= nil) then
		VentsMap[Ventend.name].Visible = false
	end
end

Ventend.TouchEnded:Connect(VentHit)

end
1 Like

You can call the VentHit() function directly after the Instance:Destroy()
Also, change the names of the functions and make the different.

Whoops, when I copied the code, it is supposed to be for the second one, VentHitend()

I wouldn’t exactly rely on TouchEnded for using part detection, it can work as a very unreliable Event when detecting part physics, since it may result in both firing & spamming the Event a lot of times

You could just implement a debounce for all of the Vents as well to prevent spam in your regular Touched event

I’m still a bit confused, if you could give a illustration for me I’d appreciate it :sweat_smile:

Wherever the NPC is being destroyed, inject the VentHitEnd() function right there.

I solved it! I basically put one in workspace (for testing) and added a script that waits 25 seconds and destroys the npc and the detector disappeared! So as of right now here’s the new code:

for x,Vent in pairs(VentsFolder:GetChildren()) do

function VentHit(hit)
	if (hit.Parent:FindFirstChild("Humanoid") ~= nil) then
		VentsMap[Vent.name].Visible = true
		print("Touch started")
	end
end

Vent.Touched:Connect(VentHit)

end

for x,Ventend in pairs(VentsFolder:GetChildren()) do

function VentHitend(hit)

	VentsMap[Ventend.name].Visible = false
	print("Touch Ended")

end

Ventend.TouchEnded:Connect(VentHitend)

end
1 Like