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?
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