Auto money giver for specific team not working correctly

I have this script for if the player is in a team that ISN’T the Resident team then they will get money every 10 seconds. The problem is that if the player changes to a team that still isn’t the resident team then what happens is the loop that counts down doesn’t stop and just stacks on top of one another making it go really fast.

ServerScript:

ReplicatedStorage.Remotes.teamUnempty.OnServerEvent:Connect(function(player, team) -- fires when the player changes teams
	if #team:GetPlayers() > 0 then
		ReplicatedStorage.Remotes.teamUnempty:FireAllClients(team) --irrelivant gui stuff
	end

	if player.Team == resident then	
		ReplicatedStorage.Remotes.noAutoCash:FireClient(player) --changes gui to show not available
	end

	task.spawn(function()
		while true do
			if player.Team ~= resident then
				player:WaitForChild("autoCashTime").Value = 10 --resets value to 10

				for i = 10, 0, -1 do --count down timer loop
					task.wait(1)
					
					player:WaitForChild("autoCashTime").Value -= 1
					
					if player.Team == resident then -- if player team becomes resident while loop is going then reset, change gui and return to exit loop
						player:WaitForChild("autoCashTime").Value = 10
						ReplicatedStorage.Remotes.noAutoCash:FireClient(player)
						return 
					end
				end

				player:WaitForChild("leaderstats"):WaitForChild("Cash").Value += 100 --at end of loop give player +100 money
			else
				return
			end

			task.wait()
		end
	end)
end)
2 Likes

Hi HecknIrishMan,

As a short-term solution:
Swap where you have return to break.

It still does the same as before.

You are creating a new task when they are choosing a new team. Remove task.spawn and this should fix it.

It is still happening the same. Not sure what is going on.

Try to get their team before the loop and if team changes then return

local Team = player.Team -- before while loop
...
if player.Team ~= Team then return end -- if team changed then stop (should be after taskwait in for loop)
1 Like

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