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

I wan't to make a random map chooser, but i can't seem to make it choose randomly?

Asked by 4 years ago

I was wondering if anyone can help

local remoteEvent = waitForChild(game:GetService("ReplicatedStorage"), "Event")
local mapsStorage = waitForChild(game:GetService("ServerStorage"), "Maps"):GetChildren() -- I want this bit to randomly choose a map instead of only choosing the first one

local playersService = game:GetService("Players")

function minigameModule.isPotentialGame()
    return playersService.NumPlayers >= settingsModule.minimumPlayers
end

function minigameModule:chooseMap()
    local chosenMap = mapsStorage[#mapsStorage]:Clone()
    if findFirstChild(chosenMap, "Spawns") then
        chosenMap.Parent = workspace
        chosenMap:MakeJoints()
        self.currentMap = chosenMap
        return chosenMap
    end
end

2 answers

Log in to vote
1
Answered by
jf_root 40
4 years ago

The length unary operator # returns the length of the operand; in this case, the operand is your table mapStorage. Since the length of the table is (presumably) fixed, the number it returns will be constant. So if mapStorage has a length of 5, you're always accessing the fifth element in the table w/ mapsStorage[#mapsStorage].

You want to pick one of the maps randomly, we can achieve this using the Random datatype.

local remoteEvent = waitForChild(game:GetService("ReplicatedStorage"), "Event")
local mapsStorage = waitForChild(game:GetService("ServerStorage"), "Maps"):GetChildren() -- I want this bit to randomly choose a map instead of only choosing the first one

local playersService = game:GetService("Players")

local R = Random.new()

function minigameModule.isPotentialGame()
    return playersService.NumPlayers >= settingsModule.minimumPlayers
end

function minigameModule:chooseMap()
    local chosenMap = mapsStorage[R:NextInteger(1, #mapsStorage)]:Clone()
    if findFirstChild(chosenMap, "Spawns") then
        chosenMap.Parent = workspace
        chosenMap:MakeJoints()
        self.currentMap = chosenMap
        return chosenMap
    end
end

0
Thank you! Bssiemeow 30 — 4y
0
But for some reason it chooses the map then kills me instantly after teleporting me? Bssiemeow 30 — 4y
Ad
Log in to vote
0
Answered by
piRadians 297 Moderation Voter
4 years ago

local chosenMap = mapsStorage[#mapsStorage]:Clone()

What are you doing heere is just referencing the table's last element, which I suppose you do not want.

I assume you want a random element.

If that's the case, then you should use math.random(1,#mapsStorage) This way, the function will return a value between the table's first and last element.

So, concluding: local chosenMap = mapsStorage[math.random(1,#mapsStorage)]:Clone()

Please, upvote this if you find this useful.

Answer this question