Weird Error In My Code

Greetings Developers, My teleportation script works but there an error and im confused. like i said the script is working as supposed to but the error is just confusing me.

1 Like

Can you add a print so that I can see what touches the part?
Write this in your code

print(hit)
2 Likes

This script should work without issues, it has a better check to make sure the part that touched belongs to a model that is a character and uses the PivotTo to teleport them instead of setting the primary part’s CFrame:

local DEBOUNCE_DURATION = 3

local teleportationParts = script.Parent
local teleportPart1 = teleportationParts.Part1
local teleportPart2 = teleportationParts.Part2

local part1Debounce, part2Debounce = false, false

teleportPart1.Touched:Connect(function(otherPart)
	if part1Debounce then return end

	local model = otherPart:FindFirstAncestorWhichIsA("Model")

	if model then
		local humanoid = model:FindFirstChildWhichIsA("Humanoid")

		if humanoid then
			part1Debounce = true

			model:PivotTo(teleportPart1.CFrame + Vector3.new(0, 6, 0))
			task.wait(DEBOUNCE_DURATION)

			part1Debounce = false
		end
	end
end)

teleportPart2.Touched:Connect(function(otherPart)
	if part2Debounce then return end

	local model = otherPart:FindFirstAncestorWhichIsA("Model")

	if model then
		local humanoid = model:FindFirstChildWhichIsA("Humanoid")

		if humanoid then
			part2Debounce = true

			model:PivotTo(teleportPart2.CFrame + Vector3.new(0, 5, 0))
			task.wait(DEBOUNCE_DURATION)

			part2Debounce = false
		end
	end
end)

This error is happening because parts can touch anything, even non player objects because of this, It is touching a non-player object, the ground for example, and then searching for the humanoidrootpart of it (which doesn’t exist for a non player object) and then attempting to teleport it, which result in the error “attempt to index nil with CFrame”

To fix this, I would add an if statement checking if the part hit belongs to a player.

ex:

--- check for grammar errors as you did not provide a raw code sample
TeleportPart2.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player and player.Character then
 local hrp = player.Character:WaitForChild("HumanoidRootPart")
 hrp.CFrame = teleportPart1.CFrame + Vector3.new(0,5,8)
teleportPart1.CanTouch = false
wait(3)
teleportPart1.CanTouch = true
     end
end)
1 Like

i solved it myself but i forgot to add an if statement😭 thank you for reminding me about he if stament part that was all i needed thank you

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.