I'm trying to make a minigame that has a lobby and a map. So if a player presses a ButtonGui when he/she in the lobby he/she will be spawned on a random part (called Spawn) in the map. Can anyone help me make the script?
✓ ANSWER ACCEPTED
How to spawn players on a random part?
2 answers
✓ Accepted answer
For this, we'll need to utilize remote events. This assumes you have your spawn parts in a model or folder in workspace named Spawns.
--Local script
local button = script.Parent --your textbutton
local remote = game.ReplicatedStorage:WaitForChild("RemoteEvent")
button.MouseButton1Click:Connect(function()
remote:FireServer()
end)
--Server script
math.randomseed(tick())
local remote = Instance.new("RemoteEvent")
remote.Parent = game.ReplicatedStorage
local spawns = workspace.Spawns:GetChildren() -- a model of all the spawn bricks
remote.OnServerEvent:Connect(function(plr)
plr:LoadCharacter()
local PlayerSpawn = spawns[math.random(1,#spawns)]
plr.Character:SetPrimaryPartCFrame(CFrame.new(PlayerSpawn.Position.X,PlayerSpawn.Position.Y + 5,PlayerSpawn.Position.Z))
end)
First, make sure the random parts are in a folder called Spawns, that's inside of the map
This is a LocalScript
local RepStorage = game:GetService("ReplicatedStorage")
local ClickedEvent = RepStorage:WaitForChild("ClickedEvent")
local Player = game:GetService("Players").LocalPlayer
local PlayerGui = Player:WaitForChild("PlayerGui")
local ButtonGui = PlayerGui:WaitForChild("ButtonGui")
ButtonGui.MouseButton1Click:Connect(function()
local Character = Player.Character or Player.CharacterAdded:wait()
if (Character) then
ClickedEvent:FireServer(Character)
end
end)
This is a ServerScript
local RepStorage = game:GetService("ReplicatedStorage")
local ClickedEvent = RepStorage:WaitForChild("ClickedEvent")
ClickedEvent.OnServerEvent:Connect(function(Player, Character)
local Spawns = workspace:FindFirstChild("MapName").Spawns --// Get Spawns
if (Character and Spawns) then --// Precaution
local Spawns_ = Spawns:GetChildren()
local Spawn = math.random(1,#Spawns) --// Get random Spawn
if (Spawn and ButtonGui) then
Player:LoadCharacter()
Character:MoveTo(Spawns[Spawn]).p + Vector3.new(0,3,0) --// Teleport
end
end
end)
Hope this works
This discussion is preserved as it was. New answers, comments, and votes are closed.

3 comments
what's a server script? and where do I put it?
Thanks it worked!
accept answer if it helped