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

How to spawn players on a random part?

Asked by 6 years ago

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?

ButtonGui

2 answers

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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)
0
what's a server script? and where do I put it? backupforibam 0 — 6y
0
Thanks it worked! RealCoolGuysworld 3 — 6y
0
accept answer if it helped Gey4Jesus69 2705 — 6y
Ad
Log in to vote
0
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
6 years ago
Edited 6 years ago

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

Answer this question