How much do i need to check if a Instance Exists?

For example, if i will run a script that teleports every single player to a part in the workspace called TELEPORTPART, and the script also changes their speed to 30

My question is: to avoid errors like the script trying to use a character of a player that just left the game, i need to check for each parts existances?

Something Like:

for i,player in pairs(game.Players:GetPlayers) do
if player and player.Character and player.Character.HumanoidRootPart and player.Character.Humanoid then
player.Character.HumanoidRootPart.CFrame = workspace.TELEPORTPART.CFrame
player.Character.Humanoid.WalkSpeed = 30
end
end

That’s probably a bit excessive, you could probably shorten it to:

if player and player.Character then

end

If the character and the player exists, then the humanoid root part likely also exists

1 Like

Yeah, like @Doomcolp said, you most likely only need those. You don’t even need to check if the player exists either, because the table would include it if it did exist.

You should also be using :PivotTo instead of setting the primary part’s CFrame.

Code:

local Players = game:GetService("Players")

for i, player in Players:GetPlayers() do
	local character = player.Character
	
	if character then
		character:PivotTo(workspace.TELEPORTPART.CFrame)
		character.Humanoid.WalkSpeed = 30
	end
end
2 Likes

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