How can I stop my game from freezing

hello scripters! I have a script that regenerates (basically adds 1 every 0.5 seconds) the player’s magic, but once it gets up to the capacity the game literally freezes and when I press exit I get this error: Script timeout: exhausted allowed execution time

here’s a video of what’s happening:
https://gyazo.com/ff509960426421bf9e84238c84c952bf

here’s my script if needed:

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		local Magic = character.Magic
		local MagicCap = character.MagicCapacity
		local Filling = false
		
		while true do
			if Magic.Value < MagicCap.Value then
				Filling = true
				while Magic.Value < MagicCap.Value do
					Magic.Value += 1
					wait(0.5)
				end
				Filling = false
			end
		end
	end)
end)

all help is appreciated

try doing this

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		local Magic = character.Magic
		local MagicCap = character.MagicCapacity
		local Filling = false
		
		while true do
            wait(.1)
			if Magic.Value < MagicCap.Value then
				Filling = true
				while Magic.Value < MagicCap.Value do
					Magic.Value += 1
					wait(0.5)
				end
				Filling = false
			end
		end
	end)
end)
2 Likes