Run .Touched Event only once

I’m fairly familiar with the .Touched event and what I can do with it. One issue I have with it at the moment is getting it to only run once when a human touches a certain part (or anything really.) Is there any way to stop it from running more than once per person?

2 Likes

There’s a few ways to do this. I’m not sure, for your case, how you would like this to be setup.
Here’s a sample script that may lead you in the right direction:

--the spooky player blacklist!
local blacklist = {};

-- part you want the player to touch
local part = game.Workspace:WaitForChild("touch part");

--player service
local players = game:GetService("Players");

--this function just uses a for each loop to check for a specific player in the blacklist
function foundInList(player)
	for _,target in ipairs(blacklist) do
		if target == player then
			return true;
		end
	end
	return false;
end

--part touched event
part.Touched:connect(function(hit)
	--check if the part that touched the part..? is a player
	local player = players:GetPlayerFromCharacter(hit.Parent);
	
	if player then
		
		--check for the player in the list
		if not foundInList(player) then
			--add them to the list, because they were not in it
			table.insert(blacklist,player);
			--do stuff here
			print("Player touched part!.. for the last time!")
		end
	end
	
end);

This piece of code blacklist players after they touch the part, and doesn’t allow them to fire the print function again.

Here’s some wiki pages that you might want to look into.

https://developer.roblox.com/en-us/articles/Loops
https://developer.roblox.com/en-us/api-reference/event/BasePart/Touched
https://developer.roblox.com/en-us/articles/Function
https://developer.roblox.com/en-us/api-reference/function/Players/GetPlayerFromCharacter
https://developer.roblox.com/en-us/articles/Table

13 Likes

Don’t worry, I understand the topics you linked below; thank you for linking them anyway for others who wish to get to know this code better!

4 Likes