Much more efficient touch tracking?

I want to make a part which if you are touching you can teleport.

The issue is that I sorta made that happen but it seems really inefficient and I had to use other parts to deactivate teleportation when player is not touching the part.
This is how it looks like except invisible.
RobloxStudioBeta_JNbXWNusOF

To check if player can teleport I made a Boolean value that gets checked true if player is touching the main part and the outside parts change the value to false when touched.


This one is in starterplayerscripts
Client Code

local begin = game.ReplicatedStorage:WaitForChild("tp")
local UserInputService = game:GetService("UserInputService")


local function onInputBegan(input, gameProcessed)
	if input.KeyCode == Enum.KeyCode.F then
		--
		begin:FireServer("f")
		--
	end
end
 
UserInputService.InputBegan:Connect(onInputBegan)

This one is inside the main part.
Server Code

local begin = game.ReplicatedStorage:WaitForChild("tp")
local part = script.Parent -- this is part that player touched
local parent = script.Parent -- pointless

local function onTouch(part)
	local tpa = part.Parent.tpa
	
		tpa.Value = true
	
begin.OnServerEvent:Connect(function(plr, f)
	
	local char = plr.Character
	
	local tpa = char.tpa

		if tpa.Value == true then
		--
		if f == "f" then
		if char == part.Parent then
			char.HumanoidRootPart.CFrame = game.Workspace.Tpone.CFrame
			wait(0.3)
			tpa.Value = false
		else
			wait()
		end
		f = ""
		end	
		--
	end	
	
end)


end


part.Touched:Connect(onTouch)

So anyway I’m not asking to design whole script for me but help would be appreciated. I’m fairly new to scripting but trying to learn a lot.

Firstly, I recommend that you pull the OnServerEvent out of the Touched because every time Touched is fired you’re creating a new connection which can double up results and especially eat up memory.

Secondly, don’t use Touched to register when they enter it - instead in the OnServerEvent check if they’re inside the Part via this handy module called Zone. You can easily create a Zone for that Part using Zone.new(part) and then check if they’re in the Zone via NewZone:getPlayer(plr).

3 Likes

I knew there had to be better way of doing this. Thank you.

1 Like