Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Using math.random() to teleport players to a random spawn location?

This code picks a random spawn to teleport the character to. This code is a bit long so how would I use math.random() to make the code shorter and work more efficiently?

	local connor =(math.random(13))
	if connor == 1 then
		plr.Character:MoveTo(workspace.Spawns.S1.Position)
	elseif connor == 2 then
		plr.Character:MoveTo(workspace.Spawns.S2.Position)
	elseif connor == 3 then
		plr.Character:MoveTo(workspace.Spawns.S3.Position)
	elseif connor == 4 then
		plr.Character:MoveTo(workspace.Spawns.S4.Position)
	elseif connor == 5 then	
		plr.Character:MoveTo(workspace.Spawns.S5.Position)
	elseif connor == 6 then
		plr.Character:MoveTo(workspace.Spawns.S6.Position)	
	elseif connor == 7 then
		plr.Character:MoveTo(workspace.Spawns.S7.Position)
	elseif connor == 8 then
		plr.Character:MoveTo(workspace.Spawns.S8.Position)
	elseif connor == 9 then
		plr.Character:MoveTo(workspace.Spawns.S9.Position)
	elseif connor == 10 then
		plr.Character:MoveTo(workspace.Spawns.S10.Position)
	elseif connor == 11 then
		plr.Character:MoveTo(workspace.Spawns.S11.Position)
	elseif connor == 12 then
		plr.Character:MoveTo(workspace.Spawns.S12.Position)
	elseif connor == 13 then
		plr.Character:MoveTo(workspace.Spawns.S13.Position)
	end

5 comments

0

you could just concatenate the random number, and use that to find the child. workspace.Spawns[ "S"..connor ]

0

not sure if this will work but try doing plr.Character:MoveTo(workspace.Spawns.S[connor].Position)

0

nope that won't work, you have to concatenate.

0

or... ya do what Percil just said XD

0

fight ma, jk

1 answer

✓ Accepted answer

All the variables follow by the same name except with a different ending number which you can concatenate.

local connor = (math.random(13)) -- i like to use math.random(firstnumber, lastnumber) but personal choice

plr.Character:MoveTo(workspace.Spawns["S"..connor].Position)

Elsewise, just create a table of the objects and have it randomly choose from the table.

connortable = {workspace.S1, workspace.S2, workspace.S3, workspace.S4, workspace.S5, workspace.S6, workspace.S7, workspace.S8, workspace.S9, workspace.S10, workspace.S11, workspace.S12, workspace.S13}
connor = (math.random(1, #connortable))

plr.Character:MoveTo(connor.Position)

OR:

connortable = {"S1", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "S10", "S11", "S12", "S13"}
connor = (math.random(1, #connortable))

plr.Character:MoveTo(workspace.Spawns[connor].Position)

This discussion is preserved as it was. New answers, comments, and votes are closed.