Issue with gamemodes

  1. What do you want to achieve? I’m trying to make a round system that tps you to the arena after voting is over

  2. What is the issue? My system works but if the gamemode “decay” wins you don’t get teleported and I’m not getting any errors in the output

  3. What solutions have you tried so far? I’ve tried to move my end’s around but that hasn’t worked and I couldn’t find any topics about this on the devforum

-- a ton of other variables

local gamemodeVotes = { ["Lava"] = 0, ["Potato"] = 0, ["Classic"] = 0, ["Decay"] = 0 }

local gamemodeOptions = { ["Lava"] = "Lava", ["Potato"] = "Potato", ["Classic"] = "Classic", ["Decay"] = "Decay" }

local playerVotes = {}

local function StartVote()
	if voteInProgress then
		return
	end

	voteInProgress = true

	for gamemode, _ in pairs(gamemodeVotes) do
		gamemodeVotes[gamemode] = 0
	end
	playerVotes = {}
end

local function HandleVote(player, gamemode)
	if not voteInProgress then
		return
	end

	local voteButton = player:WaitForChild("PlayerGui"):WaitForChild("LobbyStatus"):WaitForChild("Gamemodes"):FindFirstChild(gamemode.. "Click")
	if voteButton then
		local voteText = voteButton:FindFirstChild(gamemode.."Votes")
		if voteText and voteText:IsA("TextLabel") then
			local votes = tonumber(voteText.Text)
			if votes then
				if playerVotes[player] then
					gamemodeVotes[playerVotes[player]] = gamemodeVotes[playerVotes[player]] - 1
					voteText.Text = tostring(gamemodeVotes[gamemode])
					voteText.Text = tostring(gamemodeVotes[gamemode])
				end
				playerVotes[player] = gamemode
				gamemodeVotes[gamemode] = gamemodeVotes[gamemode]+1
				voteText.Text = tostring(gamemodeVotes[gamemode])
			end
		end
	end
end

local function GetWinner()
	local maxVotes = 0
	local winningGamemode = ""
	for gamemode, votes in pairs(gamemodeVotes) do
		if votes > maxVotes then
			maxVotes = votes
			winningGamemode = gamemode
		end
	end
	return winningGamemode
end

local function decayTile()
	local tiles = Tiles:GetChildren()

	if #tiles > 0 then
		local randomIndex = math.random(1,#tiles)
		local randomTIle = tiles[randomIndex]

		spr.target(randomTIle, 1,0.8, {Transparency =1})

		spr.completed(randomTIle, function()
			randomTIle:Destroy() 
		end)				
	end
end

local function startDecay()
	local waitTime = initialWaitTime
	local startTime = tick()
	while true do
		task.wait()
		if tick() - startTime >= waitTime then
			decayTile()
			waitTime = math.max(waitTime-decayRate, minimumWaitTime)
			startTime = tick()
			print(waitTime)
		end
	end
end

local function ActivateGamemode(gamemode)
	if gamemode == "Classic" then
		game.SoundService.Music.Lobby:Stop()
	elseif gamemode == "Lava" then
		game.SoundService.Music.Lobby:Stop()
		local music = game.SoundService.Music["Rising Full"]
		music:Play()
		print("lava")
		local lava = game.Workspace.Game.Lava 
		local newSize = Vector3.new(lava.Size.X, 250, lava.Size.Z)
		local tweenInfo = TweenInfo.new(120, Enum.EasingStyle.Linear, Enum.EasingDirection.In)
		local tween = TweenService:Create(lava,tweenInfo, {Size = newSize})
		tween:Play()	
		music.Stopped:Connect(function()
			local otherMusic = game.SoundService.Music["Rising Loop"]
			otherMusic:Play()
			otherMusic.Looped = true
		end)
	elseif gamemode == "Decay" then
		startDecay()
	end
end

local function VoteEvent(player)
	local remoteEvent = ReplicatedStorage.RoundSystemEvents:WaitForChild("RemoteMouseEvent")
	remoteEvent.OnServerEvent:Connect(function(player, gamemode)
		HandleVote(player, gamemode)
	end)
end

local function UpdateText(msg, visible)
	updateText:FireAllClients(msg, visible)
end

local function queuePlayers()
	if gameActive.Value == false then
		for i, player in pairs(Players:GetPlayers()) do
			if not table.find(queuedPlayers, player.UserId) then
				table.insert(queuedPlayers, player.UserId)
			end
		end
	end
end

Players.PlayerAdded:Connect(queuePlayers)


local function removePlayer(player)
	local id = player.UserId

	if table.find(activePlayers,id) then
		table.remove(activePlayers,table.find(activePlayers,id))
	end
	if table.find(queuedPlayers,id) then
		table.remove(queuedPlayers,table.find(queuedPlayers,id))
	end
end
Players.PlayerRemoving:Connect(removePlayer)

local function CheckForPlayers()
	while task.wait(1) do
		if gameActive.Value == true or countingDown.Value == true then return end

		queuePlayers()

		if #queuedPlayers >= config.MinimumPlayers then
			countingDown.Value = true
			StartVoteEvent:FireAllClients()
			StartVote()
			VoteEvent()
			game.SoundService.Music["Rising Full"]:Stop()
			game.SoundService.Music["Rising Loop"]:Stop()
			if	game.SoundService.Music.Lobby.Playing == false then
				game.SoundService.Music.Lobby:Play()
			end
		else
			UpdateText("Waiting for players...", true)
		end	
	end
end

CheckForPlayers()

local function gameStart(Player)
	local playersSetup = {}
	EndVoteEvent:FireAllClients()
	while true do
		for i, player in pairs (Players:GetPlayers()) do
			local userId = player.UserId

			if table.find(queuedPlayers, userId) and not playersSetup[userId] then
				table.remove(queuedPlayers, table.find(queuedPlayers,userId))
				table.insert(activePlayers, userId)
				local winningGamemode =  GetWinner()

				ActivateGamemode(winningGamemode)

				playersSetup[userId] = true
				local character = player.Character
				local humanoid = character.Humanoid
				local HumanoidRootPart = character.HumanoidRootPart
				local spawnNumber = math.random(1, #spawns:GetChildren())
				local spawnHexagon = spawns[spawnNumber]

				if spawnHexagon.Occupied.Value == false then
					spawnHexagon.Occupied.Value = true
					HumanoidRootPart.CFrame = spawnHexagon.CFrame + Vector3.new(0,5,0)
				else
					repeat 
						task.wait()
						spawnNumber = math.random(1, #spawns:GetChildren())
						spawnHexagon = spawns[spawnNumber]
					until spawnHexagon.Occupied.Value == false

					spawnHexagon.Occupied.Value = true
					HumanoidRootPart.CFrame = spawnHexagon.CFrame + Vector3.new(0,5,0)
				end

				HumanoidRootPart.CFrame = spawnHexagon.CFrame + Vector3.new(0,5,0)

				local deathConnection
				deathConnection = humanoid.Died:Connect(function()
					removePlayer(player)
					deathConnection:Disconnect()

				end)
			end
		end

		if #activePlayers == 1 then


			local winner = Players:GetPlayerByUserId(activePlayers[1])
			local hasGamepass = false
			local success, errorMsg = pcall(function()
				hasGamepass = MarketPlaceService:UserOwnsGamePassAsync(winner.UserId, GAME_PASS_ID)
			end)
			removePlayer(winner)
			UpdateText(winner.Name.. " has won!", true)
			if hasGamepass then
				winner.Stats.Wins.Value += 1
				winner.Stats.Coins.Value += 50 *1.3
				winner.Stats.XP.Value += 40 *1.5
				print("winner has vip")
			else
				winner.Stats.Wins.Value += 1
				winner.Stats.Coins.Value += 50
				winner.Stats.XP.Value += 40 
				print("Winner doesnt have vip")
			end
			task.wait(5)
			winner.Character.HumanoidRootPart.CFrame = workspace["Waiting Area"].Spawns.SpawnLocation.CFrame + Vector3.new(0,5,0)

			gameActive.Value = false
			CheckForPlayers()
			local folders = ServerStorage:GetChildren()

			local existingGameFolder = game.Workspace:FindFirstChild("Game")
			if existingGameFolder then
				existingGameFolder:Destroy()
			end

			if #folders > 0 then
				local randomFolder = folders[math.random(1, #folders)]
				local clonedFolder = randomFolder:Clone()
				clonedFolder.Parent = game.Workspace
				spawns = game.Workspace.Game.Spawns
			else
				warn("There are no maps in ServerStorage.")
			end

			break

		end
		task.wait(1)
	end
end

countingDown.Changed:Connect(function()
	if countingDown.Value == true then
		for i= config.countdownTime,0,-1 do

			if #queuedPlayers < config.MinimumPlayers then
				countingDown.Value = false
				CheckForPlayers()
				return
			end

			task.wait(1)
			UpdateText("Starting in "..i.." seconds!", true)
		end
		if #queuedPlayers < config.MinimumPlayers then
			countingDown.Value = false
			task.wait(1)
			CheckForPlayers()
			return
		end

		countingDown.Value = false
		gameActive.Value = true
		UpdateText(" ", false)
		gameStart()
	end
end)

Any help is appreciated!

1 Like

Could you may only post the important parts of the code? I think no one here wants to study the code, that would take very long

Yeah, my apologies.

local function decayTile()
	local tiles = Tiles:GetChildren()

	if #tiles > 0 then
		local randomIndex = math.random(1,#tiles)
		local randomTIle = tiles[randomIndex]

		spr.target(randomTIle, 1,0.8, {Transparency =1})

		spr.completed(randomTIle, function()
			randomTIle:Destroy() 
		end)				
	end
end

local function startDecay()
	local waitTime = initialWaitTime
	local startTime = tick()
	while true do
		task.wait()
		if tick() - startTime >= waitTime then
			decayTile()
			waitTime = math.max(waitTime-decayRate, minimumWaitTime)
			startTime = tick()
			print(waitTime)
		end
	end
end

local function ActivateGamemode(gamemode)
	if gamemode == "Classic" then
		game.SoundService.Music.Lobby:Stop()
	elseif gamemode == "Lava" then
		game.SoundService.Music.Lobby:Stop()
		local music = game.SoundService.Music["Rising Full"]
		music:Play()
		print("lava")
		local lava = game.Workspace.Game.Lava 
		local newSize = Vector3.new(lava.Size.X, 250, lava.Size.Z)
		local tweenInfo = TweenInfo.new(120, Enum.EasingStyle.Linear, Enum.EasingDirection.In)
		local tween = TweenService:Create(lava,tweenInfo, {Size = newSize})
		tween:Play()	
		music.Stopped:Connect(function()
			local otherMusic = game.SoundService.Music["Rising Loop"]
			otherMusic:Play()
			otherMusic.Looped = true
		end)
	elseif gamemode == "Decay" then
		startDecay()
	end
end

--skipping some functions

local function gameStart(Player)
	local playersSetup = {}
	EndVoteEvent:FireAllClients()
	while true do
		for i, player in pairs (Players:GetPlayers()) do
			local userId = player.UserId

			if table.find(queuedPlayers, userId) and not playersSetup[userId] then
				table.remove(queuedPlayers, table.find(queuedPlayers,userId))
				table.insert(activePlayers, userId)
				local winningGamemode =  GetWinner()

				ActivateGamemode(winningGamemode)

				playersSetup[userId] = true
				local character = player.Character
				local humanoid = character.Humanoid
				local HumanoidRootPart = character.HumanoidRootPart
				local spawnNumber = math.random(1, #spawns:GetChildren())
				local spawnHexagon = spawns[spawnNumber]

				if spawnHexagon.Occupied.Value == false then
					spawnHexagon.Occupied.Value = true
					HumanoidRootPart.CFrame = spawnHexagon.CFrame + Vector3.new(0,5,0)
				else
					repeat 
						task.wait()
						spawnNumber = math.random(1, #spawns:GetChildren())
						spawnHexagon = spawns[spawnNumber]
					until spawnHexagon.Occupied.Value == false

					spawnHexagon.Occupied.Value = true
					HumanoidRootPart.CFrame = spawnHexagon.CFrame + Vector3.new(0,5,0)
				end

				HumanoidRootPart.CFrame = spawnHexagon.CFrame + Vector3.new(0,5,0)

				local deathConnection
				deathConnection = humanoid.Died:Connect(function()
					removePlayer(player)
					deathConnection:Disconnect()

				end)
			end
		end

		if #activePlayers == 1 then


			local winner = Players:GetPlayerByUserId(activePlayers[1])
			local hasGamepass = false
			local success, errorMsg = pcall(function()
				hasGamepass = MarketPlaceService:UserOwnsGamePassAsync(winner.UserId, GAME_PASS_ID)
			end)
			removePlayer(winner)
			UpdateText(winner.Name.. " has won!", true)
			if hasGamepass then
				winner.Stats.Wins.Value += 1
				winner.Stats.Coins.Value += 50 *1.3
				winner.Stats.XP.Value += 40 *1.5
				print("winner has vip")
			else
				winner.Stats.Wins.Value += 1
				winner.Stats.Coins.Value += 50
				winner.Stats.XP.Value += 40 
				print("Winner doesnt have vip")
			end
			task.wait(5)
			winner.Character.HumanoidRootPart.CFrame = workspace["Waiting Area"].Spawns.SpawnLocation.CFrame + Vector3.new(0,5,0)

			gameActive.Value = false
			CheckForPlayers()
			local folders = ServerStorage:GetChildren()

			local existingGameFolder = game.Workspace:FindFirstChild("Game")
			if existingGameFolder then
				existingGameFolder:Destroy()
			end

			if #folders > 0 then
				local randomFolder = folders[math.random(1, #folders)]
				local clonedFolder = randomFolder:Clone()
				clonedFolder.Parent = game.Workspace
				spawns = game.Workspace.Game.Spawns
			else
				warn("There are no maps in ServerStorage.")
			end

			break

		end
		task.wait(1)
	end
end

these should be the important functions.

Try printing the values the if statement needs:

	while true do
		task.wait()
        print("startTime = ", startTime, "     waitTime = ", waitTime)
		if tick() - startTime >= waitTime then
			decayTile()
			waitTime = math.max(waitTime-decayRate, minimumWaitTime)
			startTime = tick()
			print(waitTime)
		end
	end

[/quote]

None of these actually print as my game wont start meaning the game cant activate a gamemode

Alright I’ve fixed the issue with my game not starting the only problem now is that I don’t get teleported to one of the ingame spawns

1 Like

Then use other prints to see why if statements aren’t firing. Like this:

local function ActivateGamemode(gamemode)
    print("gamemode = ",gamemode)  -- if Decay doesn't print then you need to find out why.
	if gamemode == "Classic" then
1 Like

Decay does print and everything else is functional including the gamemode I just need to figure out why the game doesn’t teleport me to any spawns if decay is voted.

Could it potentially be that this is an infinite loop yielding the function forever?

1 Like

I believe it is, I’ve just added a few prints and it prints everything until my activategamemode function is called although I don’t know how to combat this

1 Like

A potential solution would be to add a value that checks when the game ends and detect whether it happened. Maybe you could do something like this?

local function startDecay()
	local waitTime = initialWaitTime
	local startTime = tick()
	while true do
		task.wait()
		if check then break end -- cancels out the rest of the code and ends the loop
		if tick() - startTime >= waitTime then
			decayTile()
			waitTime = math.max(waitTime-decayRate, minimumWaitTime)
			startTime = tick()
			print(waitTime)
		end
	end
end

Heres what I have now

local function startDecay()
	local waitTime = initialWaitTime
	local startTime = tick()
	while true do
		task.wait()
		if gameActive.Value == false then break end
		if tick() - startTime >= waitTime then
			decayTile()
			waitTime = math.max(waitTime-decayRate, minimumWaitTime)
			startTime = tick()
			print(waitTime)
		end 
	end
end

and now the loop doesn’t run at all even if gameactive is true

Do you set the gameActive value before this function?

Woops, I had an oversight I called the function before setting gameactive but it’s still not teleporting me into the arena for some reason.

local function startDecay()
	local waitTime = initialWaitTime
	local startTime = tick()
	while true do --This loop seems to yield the activate gamemode function forever try putting it in task.spawn()
		task.wait()
		if tick() - startTime >= waitTime then
			decayTile()
			waitTime = math.max(waitTime-decayRate, minimumWaitTime)
			startTime = tick()
			print(waitTime)
		end
	end
end

It seems that the startDecay function has a infinite loop in it which may cause your script to yield forever whenever the function gets called try putting it in task.spawn to create another thread for this loop like this:

task.spawn(function()
	while true do
		--code here
	end
end)

Let me know if you are confused i am happy to help!

NOTE:

You can actually store the thread returned by task.spawn so you can task.cancel the thread after the match ends so the loop doesnt go on forever ( you can also use break and check when the match ended to end the loop ). EXAMPLE:

local decayLoopThread -- variable at the start of the script

decayLoopThread = task.spawn(function() -- define it as the thread
	while true do
		--code here
	end
end)

if matchIsOver then
	if gamemode == "Decay" and type(decayLoopThread) == "thread" then --You can put this whenever the match ends
		task.cancel(decayLoopThread)
		decayLoopThread = nil
	end
end
1 Like

This worked thank you so much! :slight_smile:

One more question. Does the loop go on even after the match ends? (if so you can check out the NOTE section i wrote and ask anymore questions you have)

No I’ve added a check for that

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.