Trying to make value count number of seconds a player has had ownership

local RS = game:GetService("ReplicatedStorage")
local Event = RS:WaitForChild("ChangeOwner")
local Event2 = RS:WaitForChild("ChangeValue")
local cooldown = .6


local function GiveTeamTouches(TeamName,Amount)
	for _,player in pairs(game.Players:GetChildren()) do
		if player.Team.Name == TeamName then
			print(player.Team.Name .. " has touched the ball")
			while true do
				player.MatchStats.TimeOnBall.Value += Amount
				print("Gave player touch")
				task.wait(1)
			end
		end
	end
end

local function TimeOnBall(object)
	for index,v in pairs(game.Players:GetPlayers()) do
		if v == object.Owner.Value then
			if v.Team == game.Teams.Red then
				while true do
					GiveTeamTouches("Red", 1)
					print("Gave player a touch")
				end
			elseif v.Team == game.Teams.Green then
				while true do
					GiveTeamTouches("Green", 1)
					print("Gave player a touch")
					task.wait(1)
				end
			end
		end
	end
end

Event.OnServerEvent:connect(function(player, ball)
	if ball.Name ~= "TPS" then return end
	if not ball.Owner.Value == nil then
		player.MatchStats.Tackles.Value += 1
	end
	ball:SetNetworkOwner(player)
	
	ball.Owner.Value = ball:GetNetworkOwner()
	ball.ReactDecline.Value = true
	local reactbub = Instance.new("Part")
	reactbub.Shape = Enum.PartType.Ball
	reactbub.Size = Vector3.new(.5,.5,.5)
	reactbub.CanCollide = false
	reactbub.Anchored = true
	reactbub.Material = Enum.Material.ForceField
	reactbub.BrickColor = player.TeamColor
	reactbub.Transparency = 0
	reactbub.Name = "ReactBubble"
	reactbub.Position = ball.Position
	reactbub.Parent = workspace
	reactbub:Clone()
	
	
	local tweenService = game:GetService("TweenService")
	local toTween = reactbub
	local goals = {Size=Vector3.new(3.5,3.5,3.5)}

	local tweenInfo = TweenInfo.new(

		.5,
		Enum.EasingStyle.Sine,
		Enum.EasingDirection.Out,
		0,
		false,
		0
	)

	tweenService:Create(toTween,tweenInfo,goals):Play()
	
	wait(cooldown)
	reactbub:Destroy()
	TimeOnBall(game.Workspace.Balls:WaitForChild("TPS"))
	ball.ReactDecline.Value = false
end)

I am trying to make it count the number of seconds the player has had the ball but since the while loop is happening the event doesn’t end so the other player can’t hit it any help is appreciated.

1 Like

wrap a coroutine/task.spawn to create another thread so that your code can run simultaneously and react to any listener events.

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