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

Random spawning not working?

Asked by 9 years ago

In a script I made, people were supposed to spawn in random spawns, it should be working but the output is saying that it isn't.

Variable

spawns = game.Workspace.Spawns:FindFirstChild("Play" .. tostring(math.random(1, 6)))

9 lines down

For statement using Variable

for i,v in pairs(game.Players:GetPlayers()) do
    v.Character:MoveTo(spawns.Position)
end

There are multiple spawns in a model inside workspace, all players are supposed to spawn in one of them each. So I used a for statement to get it random.

Output

Workspace.Game:11: attempt to index global 'spawns' (a nil value)

0
So, tell me if I'm correct. There is a model in Workspace called 'Spawns' (exactly spelt like that) and in 'Spawns' there are 10 spawns named 'Play1', 'Play2', 'Play3', 'Play4' or are they all named 'Play'? DigitalVeer 1473 — 9y
0
Wait a minute. Grenaderade 525 — 9y
0
Changed the 10 to a 6 and they are all named "Play" Grenaderade 525 — 9y

1 answer

Log in to vote
0
Answered by 9 years ago

String Concatenation

The main reason this is happening is because the compiler is looking in Workspace for the following:

Play1 Play2 Play3 Play4 Play5 Play6

This is due to the fact you are using String Concatenation with a number.

local number = 3
local string = "Play"..number
print(string)
--Play3

When you use '..' that concatenates the numbers and strings. This is where the issue comes in your script since you are looking for parts named 'Play' followed with numbers behind it.:

But since all of them are only named 'Play', that means it's looking for something that doesn't exist, hence the error you are getting:

Workspace.Game:11: attempt to index global 'spawns' (a nil value)

nil = Non-Existant

To fix this, let's look at the model 'Spawns' and search for parts that only have 'Play' in the name. We will create a function to obtain a random Spawn from the 'Spawns' model.

function getRandomSpawn()
local spawns = workspace["Spawns"]:GetChildren()
return spawns[math.random(#spawns)]
end

for _,plr in pairs(game.Players:GetPlayers()) do
local spawn = getRandomSpawn()
plr.Character:MoveTo(spawn.Position)
end
Ad

Answer this question