Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to choose a part with math.random (random question mark?)

I've seen a lot of people do round based games and use math.random() to choose what spawn the player goes to. I've been running into a lot of trouble with this. Whenever I use it it tells me that whatever number it came up with is not a valid object in spawns.

Script:

local Spawns = workspace.MapStorage.Map:GetChildren()
local chosenmap = math.random(1,#Spawns)

for i, v in pairs(game.Players:GetPlayers()) do
	local name = v.Name
	if workspace:FindFirstChild(name) then
		workspace[name].Torso.CFrame = CFrame.new(workspace.MapStorage.Map[chosenmap].Position)
	end
end

I also have a script that changes the spawns parent so it can't be used again until the end of the round where the main script puts it back.

1 answer

✓ Accepted answer

First you have to make a random number variable.

local RandomMapNumber

Lets say you have 3 maps.

local RandomMapNumber = math.random(1, 3)

Get the maps from serverstorage.

local ServerStorage = game:GetService('ServerStorage')

local map1 = ServerStorage:WaitForChild('map1name')
local map2 = ServerStorage:WaitForChild('map2name')
local map3 = ServerStorage:WaitForChild('map3name')

Next, you have to make a function to choose a random map.

function randomMap()
	RandomMapNumber = math.random(1, 3)
	
	if (RandomMapNumber == 1) then 
		local map1clone = map1:Clone()
		map1clone.Parent = workspace

	elseif (RandomMapNumber == 2) then 
		local map2clone = map2:Clone()
		map2clone.Parent = workspace

	elseif (RandomMapNumber == 3) then 
		local map3clone = map3:Clone()
		map3clone.Parent = workspace
	end
end

Hope this helped. GL

1 comment

0

thanks

This discussion is preserved as it was. New answers, comments, and votes are closed.