Detect Touch only once per player life

  1. What do you want to achieve?
    I want to make a system that when a player touches a part it, lets just say for this post, print a message but doesnt print it again when they touch it for a second time until the player has died and respawned

  2. What is the issue?
    i know how to use Touch but have zero idea on how to go about making something like this

  3. What solutions have you tried so far?
    Havent found any solution for this issue yet

this is the code i am currently using, it spams the print which isnt what i want

function onTouched(hit)
	local h = hit.Parent:FindFirstChild("Humanoid")
	local Players = game:GetService("Players")
	if h ~= nil then
		print("hello")
	end
end

script.Parent.Touched:Connect(onTouched)

Add a boolvalue to the player, when they touch the part then it becomes true. Check when its touched if the bool value is false to show a print. Then used the Humanoid.Died event to reset the bool value.

1 Like

any chance that you could give an example of that?

Sure,

-- Touch Script
function onTouched(hit)
	local h = hit.Parent:FindFirstChild("Humanoid")
	local Players = game:GetService("Players")
	if h then
		if h.BoolValue.Value then
h.BoolValue.Value = false
print("Hello")
	end
end

script.Parent.Touched:Connect(onTouched)

-- Local Script in StarterCharacterScripts
local Character = game.Players.LocalPlayer.Character or game.Players.LocalPlayer.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
Humanoid.Died:Connect(function()
     Humanoid.BoolValue.Value = true
end

Also use the PlayerAdded event to insert a value into the player that joined.

1 Like

Alternatively use a custom attribute, which would be much cleaner than instantiating and maintaining a value object.

-- Touch Script
function onTouched(hit)
	local h = hit.Parent:FindFirstChild("Humanoid")
	local Players = game:GetService("Players")
	if h ~= nil and not h:GetAttribute("TouchedOnce") then
		print("hello")
        h:SetAttribute("TouchedOnce", true)
	end
end

script.Parent.Touched:Connect(onTouched)

There is no need for the bottom part of your script because the Humanoid gets reset every time the player respawns anyway.

4 Likes

Thank you and @10kgoldxdrip for the help :DD