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

How do I use touched event with changing value?

I am making a game where a certain event happens when a certain player touches another player, but to do this I will have to have the 'touch' event. I tried running this (the value changes from another script) but it does not work.

plr = game.ReplicatedStorage.Values.current_plr.Value
game.ReplicatedStorage.Values.current_plr.Changed:Connect(function()
	plr = game.ReplicatedStorage.Values.current_plr.Value
end)
game.Workspace[plr].Torso.Touched:Connect(function(p)
	print("plr was touched")
end)

1 answer

✓ Accepted answer

It's not working because an event does not reconnect it just connects to the original object, in this instance the first [plr].Torso. So to do something closer to what you want to do you can try:

local plr = game.ReplicatedStorage.Values.current_plr.Value
local connection
game.ReplicatedStorage.Values.current_plr.Changed:Connect(function()
	plr = game.ReplicatedStorage.Values.current_plr.Value
	if connection ~= nil then
		connection:disconnect() --This if statement is done to remove the previous connection
	end --Otherwise we would have the potential to leak connected instances.
	connection = game.Workspace[plr].Torso.Touched:connect(function(p)
		print("plr was touched") --Set up the new touch connection
	end)
end)

Basically, you just have to nest them and not forget to disconnect previous connections. Hope that helped if you have questions feel free to post back!

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