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

Teleporting to random brick?

for i,v in pairs(game.Workspace:GetDescendants()) do
	if v.Name == "Spawnpoint" then
		local choice = v:GetChildren()
		local ChosenSpawn = choice[math.random(0, #choice)]
		wait()
		game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = ChosenSpawn.CFrame
	end
end

I'm trying to make a script that finds all parts called "Spawnpoint" and then picks a random one, then teleports the player to it. I was getting errors when I did

choice[math.random(1, #choice)]

bad argument #2 to 'random' (interval is empty)

I don't know if I've fixed it but now I keep getting this error: attempt to index local 'ChosenSpawn' (a nil value) Can anyone help me?

1 answer

alert sound ! "attempt to index local 'ChosenSpawn' (a nil value)". This implies that "local ChosenSpawn = choice[math.random(0, #choice)] " is nil. If you choose a spawnpoint, I presume there isn't going to be another part inside that, as you were declaring "choice" as a table full of children of the spawn point. Try caching the spawnpoints inside a table, and randomly choosing one from that. If you have very few instances in workspace, you could just choose a random one then check its name.

local choices = {}
for i,v in pairs(game.Workspace:GetDescendants()) do
    if v.Name == "Spawnpoint" then
	table.insert(choices, v) -- cache choices into a table
        local ChosenSpawn = choices[math.random(0, #choices)] -- select a spawn from cached options
        wait()
        game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = ChosenSpawn.CFrame
	choices = nil
    end
end

2 comments

0

bad argument #1 to 'insert' (table expected, got nil) The script teleports me to only one part, none of the others, any way to fix?

0

Ah. line 8 should be "choices = {}"

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