Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Teleporting to random brick?

Asked by
trecept 367 Moderation Voter
6 years ago
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

Log in to vote
0
Answered by
H4X0MSYT 536 Moderation Voter
6 years ago
Edited 6 years ago

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

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? trecept 367 — 6y
0
Ah. line 8 should be "choices = {}" H4X0MSYT 536 — 6y
Ad

Answer this question