So this script is a simple map changer. However, everytime when a new player joins, another map spawns for some reason, any help? thank you.
local MapsFolder = game.ReplicatedStorage.Maps
local Maps = MapsFolder:GetChildren()
local RoundTime = script.RoundTime
local IntermermissionTime = script.IntermissionTime
game.Players.PlayerAdded:Connect(function(player)
while true do
local ChosenMap = Maps[math.random(1,#Maps)]
local MapClone = ChosenMap:Clone()
task.wait(IntermermissionTime.Value)
MapClone.Parent = game.Workspace
MapClone:MakeJoints()
player:LoadCharacter()
task.wait(RoundTime.Value)
MapClone:Destroy()
end
end)
The function you pass to the PlayerAdded event will execute every time a new player joins the game. In this case, an infinite loop is established and will run forever. This happens each time a player joins the game; therefore causing numerous maps to load. Additionally, this wouldn’t be good for performance as those infinite loops will never stop executing.
The easy solution here is to define your loop outside of the player added event, and then utilize a player count check instead to determine when the game should start.
So, for example you could do something like:
local function canGameBegin() --//Start the game when ever 2 or more players are in the server
return #game.Players:GetPlayers() >= 2
end
while canGameBegin() do
local ChosenMap = Maps[math.random(1,#Maps)]
local MapClone = ChosenMap:Clone()
task.wait(IntermermissionTime.Value)
MapClone.Parent = game.Workspace
MapClone:MakeJoints()
task.wait(RoundTime.Value)
MapClone:Destroy()
end
I was trying to get the players in the first place so that everytime it is the next map, the players respawn. I also want it to be able so that it can just be one player on the map.
I’m not entirely sure what your goal is here, but I’d recommend trying to determine your game flow logic, and then build your code around that.
One suggestion is using an event binding that executes each time the player’s character loads in (CharacterAdded), and then checking to see what map exists, and finally teleporting the player to that map.
I made the script to just make a basic round system. No lobby intended. It is basically a fighting game. So the maps just have spawn points placed around the maps. I wanted to make it so that the maps just change, which I did. Then I wanted to make it so the players just respawn when the next map is on, because I don’t want them just fall in the void. It worked, however, when another player join, it will for some reason bring another map out.