Reading variable with task.spawn() not working as expected

This is probably due to me misunderstanding how this works, but here is my code:

local lastTick

task.spawn(function() 
    lastTick = tick()
    local thisTick = lastTick
    print("OLD: "..lastTick)
						
    plr.PlayerGui.Hitmarker.Enabled = true 
    task.wait(.2) 
    print("NEW: "..lastTick)
						
    if lastTick == thisTick then
        plr.PlayerGui.Hitmarker.Enabled = false 
    end					
end)

The idea is that lastTick will be readable by all future task.spawn() functions, while thisTick is only visible by the current one. Therefore, lastTick will be updated by every function and will be different for each function call except from the last one that happens within the 0.2 seconds.

However, every time lastTick is updated, the task.spawn() function still reads the original value in the if statement. This is the output I get:

As you can see, lastTick has not changed by the time it reaches the if statement. By the time the function runs for a second time, lastTick should have increased in value.

How would I get each task.spawn() function to read the updated value of lastTick?

Switch the first two lines of the function.

Actually I just figured it out - it’s because the entire thing was in a tool.Activated event, so I moved lastTick outside of the event and it works :slight_smile:

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