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

How do I make this spawn 1 player per spawner? Help?

Asked by 7 years ago

So, This brings all players in the server to a spawner, but the problem is they all go to the same spawner. I need 1 player per spawner. (6 Spawners total)

function BringPlayers()
    Spawns = game.Workspace.MapSpawners:GetChildren()
    local SelectedSpawn = math.random(1,#Spawns)
    local Spawn = Spawns [SelectedSpawn]

    local Players = game.Players:GetPlayers()
    for i = 1, #Players do
    Players[i].Character.UpperTorso.CFrame = CFrame.new(Spawn.SpawnPart.Position)
    end
    end

2 answers

Log in to vote
0
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
7 years ago
Edited 7 years ago

You need to define the Spawn and SelectedSpawn varaibles inside of the for loop, so that the math.random result varies :)

EDIT: Remove values from the 'Spawns' table, using the table.remove function to ensure nobody gets duplicate spawns :)

function BringPlayers()
    local Spawns = workspace.MapSpawners:GetChildren()
    local Players = game.Players:GetPlayers()
    for i = 1, #Players do
        --Define inside for loop
        --EDIT: table.remove to ensure no duplicates
        local SelectedSpawn = table.remove(Spawns,math.random(#Spawns))
        local Spawn = Spawns[SelectedSpawn]
        if Players[i].Character then --Make sure they are spawned in
            --Rootpart for R6/R15 compatibility
            local root = Players[i].Character.HumanoidRootPart
            root.CFrame = Spawn.SpawnPart.CFrame
        end
    end
end
0
Thanks! IfIWasntSoSwag 98 — 7y
1
But there is still a possibly that two players spawn at the same location. Bluemonkey132 194 — 7y
0
You're right Bluemonkey ;D table.remove applied. Goulstem 8144 — 7y
Ad
Log in to vote
1
Answered by 7 years ago

The problem is that you select only one random spawn location for everyone. Try this:

function BringPlayers()
    local Spawns = game.Workspace.MapSpawners:GetChildren()
    local UsedSpawns = {}
    local Players = game.Players:GetPlayers()
    for i = 1, #Players do
        local SelectedSpawn = math.random(1,#Spawns)
        local AlreadyUsed = true
        while AlreadyUsed do
            AlreadyUsed = false
            for i,v in pairs(UsedSpawns) do
                if v == SelectedSpawn then
                    AlreadyUsed = true
                end
            end
            if AlreadyUsed then
                SelectedSpawn = math.random(1,#Spawns)
            end
        end
        table.insert(UsedSpawns, SelectedSpawn)
        local Spawn = Spawns[SelectedSpawn]
        Players[i].Character.UpperTorso.CFrame = CFrame.new(Spawn.SpawnPart.Position)
    end
end

This while loop keeps trying to find an unused spawn location. There might be a more efficient way of doing this but this is what I thought of.

Answer this question