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?
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
.
01 | --Local script |
02 |
03 | local button = script.Parent --your textbutton |
04 | local remote = game.ReplicatedStorage:WaitForChild( "RemoteEvent" ) |
05 |
06 | button.MouseButton 1 Click:Connect( function () |
07 | remote:FireServer() |
08 | end ) |
09 |
10 | --Server script |
11 | math.randomseed(tick()) |
12 | local remote = Instance.new( "RemoteEvent" ) |
13 | remote.Parent = game.ReplicatedStorage |
14 | local spawns = workspace.Spawns:GetChildren() -- a model of all the spawn bricks |
15 |
16 | remote.OnServerEvent:Connect( function (plr) |
17 | plr:LoadCharacter() |
18 | local PlayerSpawn = spawns [ math.random( 1 ,#spawns) ] |
19 | plr.Character:SetPrimaryPartCFrame(CFrame.new(PlayerSpawn.Position.X,PlayerSpawn.Position.Y + 5 ,PlayerSpawn.Position.Z)) |
20 | end ) |
First, make sure the random parts are in a folder called Spawns, that's inside of the map
This is a LocalScript
01 | local RepStorage = game:GetService( "ReplicatedStorage" ) |
02 | local ClickedEvent = RepStorage:WaitForChild( "ClickedEvent" ) |
03 | local Player = game:GetService( "Players" ).LocalPlayer |
04 | local PlayerGui = Player:WaitForChild( "PlayerGui" ) |
05 | local ButtonGui = PlayerGui:WaitForChild( "ButtonGui" ) |
06 | ButtonGui.MouseButton 1 Click:Connect( function () |
07 | local Character = Player.Character or Player.CharacterAdded:wait() |
08 | if (Character) then |
09 | ClickedEvent:FireServer(Character) |
10 | end |
11 | end ) |
This is a ServerScript
01 | local RepStorage = game:GetService( "ReplicatedStorage" ) |
02 | local ClickedEvent = RepStorage:WaitForChild( "ClickedEvent" ) |
03 | ClickedEvent.OnServerEvent:Connect( function (Player, Character) |
04 | local Spawns = workspace:FindFirstChild( "MapName" ).Spawns --// Get Spawns |
05 | if (Character and Spawns) then --// Precaution |
06 | local Spawns_ = Spawns:GetChildren() |
07 | local Spawn = math.random( 1 ,#Spawns) --// Get random Spawn |
08 | if (Spawn and ButtonGui) then |
09 | Player:LoadCharacter() |
10 | Character:MoveTo(Spawns [ Spawn ] ).p + Vector 3. new( 0 , 3 , 0 ) --// Teleport |
11 | end |
12 | end |
13 | end ) |
Hope this works