How to stop a function once that function has been fired again

So I am making a soccer game and I am adding a feature so if a player passes another player the ball and they score they get points for an assist. The way I am doing this is I added a string value inside of the ball so once the player passes the ball to another player their name is added to the string value inside of the ball. The function waits for 4 seconds then it makes the value " ". This is because after 4 seconds of having the ball it isn’t really an assist anymore. So the issue I have is that if player1 passes the ball to player2 and player2 waits 3 seconds then passes the ball back to player1. After 1 second that value will be changed to " " instead of staying as player2 for 4 seconds. It may be kind of confusing so here is the code.

local function Pass(player)
	ball.Assister.Value = player.Name	
wait(4)
	ball.Assister.Value = ""
end		

This function gets called from a remote function client to server. This code is in the server script. The client is the one who passes the ball. So how can I stop the function from changing the name back if the function gets called again. This may be a little confusing so if you have any questions I can answer them all.

function Pass(player)
    ball.Assister.Value = player.Name

    task.delay(4, function()
        if ball.Assister.Value == player.Name then
            ball.Assister.Value = ""
        end
    end)
end

does this work?

local fired = false
local function Pass(player)
	if fired == true then return end
	ball.Assister.Value = player.Name	
wait(4)
	ball.Assister.Value = ""
	fired = true
end

Issue with this is if player1 passes the ball to player2 then player2 pass it back to player1, and then player 1 passes it back to player 2 in the span of 4 seconds then the game will see that player 1 is the assister and change it to " " even though it has probably only been half a second

local Assisters = {}

function Pass(player)
    ball.Assister.Value = player.Name
    if Assisters[player.Name] then
        Assisters[player.Name] += 1
    else
        Assisters[player.Name] = 1
    end

    task.delay(4, function()
        if ball.Assister.Value = player.Name and Assisters[player.Name] == 1 then
            ball.Assister.Value = ""
        end

        Assisters[player.Name] -= 1
    end)
end

I fixed some problems

You could increment a value, and check it hasn’t incremented again when you do the deferred logic.

I’d recommend resetting the passId to 0 when a goal is scored or at kickoff to avoid it adding up forever.

local passId = 0

local function Pass(player)
	local identifier = passId + 1
	passId = identifier
	ball.Assister.Value = player.Name	
	wait(4)
	if passId ~= identifier then
		return
	end
	ball.Assister.Value = ""
end		

I use this kind of setup a lot when there’s a deferred process that needs to only occur if nothing else has taken priority.

5 Likes