Math.random doesn't do anything when teleporting players

I have a problem with the following code:

local PlayerSpawn = game.Workspace.PlayerSpawn:GetChildren()[math.random(1, #game.Workspace.PlayerSpawn:GetChildren())]
local RespawnPart = game.Workspace.RespawnPart

RespawnPart.Touched:Connect(function(TouchPart)
	if TouchPart.Parent:FindFirstChild("HumanoidRootPart") then
		TouchPart.Parent:FindFirstChild("HumanoidRootPart").CFrame = PlayerSpawn.CFrame + Vector3.new(0, 3, 0)
		wait(2.5)
		end
end)```

So basically when a player touches the Respawn Part, it is supposed to teleport them randomly on one of the 6 player spawn. But the result was the character respawning on the same spawn point on multiple attempts.

Any help is greatly appreciated.

18 Likes

I don’t know if this is the best way of implementing randomized spawns, but the issue is that the “PlayerSpawn” variable becomes set in stone.

Whichever spawn is randomly picked the first time will always be “chosen”, as it won’t randomize it again - it’s a reference to that chosen value.

If you create a function to select a random spawn and assign it to PlayerSpawn instead, that would resolve your issue.

14 Likes