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 5 years ago

I was wondering if anyone can help

01local remoteEvent = waitForChild(game:GetService("ReplicatedStorage"), "Event")
02local mapsStorage = waitForChild(game:GetService("ServerStorage"), "Maps"):GetChildren() -- I want this bit to randomly choose a map instead of only choosing the first one
03 
04local playersService = game:GetService("Players")
05 
06function minigameModule.isPotentialGame()
07    return playersService.NumPlayers >= settingsModule.minimumPlayers
08end
09 
10function minigameModule:chooseMap()
11    local chosenMap = mapsStorage[#mapsStorage]:Clone()
12    if findFirstChild(chosenMap, "Spawns") then
13        chosenMap.Parent = workspace
14        chosenMap:MakeJoints()
15        self.currentMap = chosenMap
16        return chosenMap
17    end
18end

2 answers

Log in to vote
1
Answered by
jf_root 40
5 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.

01local remoteEvent = waitForChild(game:GetService("ReplicatedStorage"), "Event")
02local mapsStorage = waitForChild(game:GetService("ServerStorage"), "Maps"):GetChildren() -- I want this bit to randomly choose a map instead of only choosing the first one
03 
04local playersService = game:GetService("Players")
05 
06local R = Random.new()
07 
08function minigameModule.isPotentialGame()
09    return playersService.NumPlayers >= settingsModule.minimumPlayers
10end
11 
12function minigameModule:chooseMap()
13    local chosenMap = mapsStorage[R:NextInteger(1, #mapsStorage)]:Clone()
14    if findFirstChild(chosenMap, "Spawns") then
15        chosenMap.Parent = workspace
16        chosenMap:MakeJoints()
17        self.currentMap = chosenMap
18        return chosenMap
19    end
20end
0
Thank you! Bssiemeow 30 — 5y
0
But for some reason it chooses the map then kills me instantly after teleporting me? Bssiemeow 30 — 5y
Ad
Log in to vote
0
Answered by
piRadians 297 Moderation Voter
5 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