Error in Portal Script

Hello so I have a portal in the beginning of my game to teleport the player to the first level. But the problem is sometimes the portal will stop working all together and the error message will be that a pet or a gravity coil is not a valid member of Players “Players”. The thing is this only happens sometimes and other times it will just work fine so its hard to gage what the problem is. What should I do to fix this issue?

local TeleportationDoorEvent  = game.ReplicatedStorage.TeleportationDoorsEvent
local Teleport = "Door2" 

function Touch(hit) 
	if script.Parent.Locked == false and script.Parent.Parent:findFirstChild(Teleport).Locked == false then script.Parent.Locked = true 
		script.Parent.Parent:findFirstChild(Teleport).Locked = true 
		
	local plr = game.Players[hit.Parent.Name]
		
	pcall(function()
		TeleportationDoorEvent:FireClient(plr)
	end)
	wait(1)	
	local Pos = script.Parent.Parent:findFirstChild(Teleport) 
		hit.Parent:FindFirstChild("HumanoidRootPart").CFrame = Pos.CFrame 
		wait(1) 
		script.Parent.Locked = false script.Parent.Parent:findFirstChild(Teleport).Locked = false 
	end 
end 
script.Parent.Touched:connect(Touch) 

You need to verify if the hit is done by a player’s character. Basically, check if Players:GetPlayerFromCharacter called on hit.Parent returns a player.

1 Like