How would i go about preventing 2 different functions clashing while changing the same value?

I come across this issue extremely often and it is always a hassle to get through and i have to come up with very hacky solutions or just scrap the idea.

The title is probably confusing so let me elaborate;

For my current use case i have an attack that anchors the player in the air for 0.6 seconds, however the player can attack again while in the air after waiting 0.3 seconds, My problem is:

The player does the attack in the air
Waits 0.3 seconds
Before being unanchored, attacks again

Now because the first script is still running the player will be unanchored after 0.3 seconds instead of the intended 0.6 seconds.

This could be fixed by somehow stopping the first function from running at the start of the second one, but i cannot find a way to do this.

Sorry if this sounded confusing- feel free to ask me anything regarding the issue that you didnt quite understand.

One solution is to create a thread for the function and using task.cancel on it later on. Example:

local attackThread: thread? = nil

local function primaryAttack(): ()
    -- after doing stuff, set attackThread to nil
    attackThread = nil
end

local function secondaryAttack(): ()
    -- after doing stuff, set attackThread to nil
    attackThread = nil
end

-- then to call your attacks
if attackThread ~= nil then
    task.cancel(attackThread)
end

attackThread = task.spawn(primaryAttack) -- or secondaryAttack

Another way is to have stackable effects, which requires a system that keeps track of states and/or flags. This is probably the more preferred solution in your case without having to create threads for multiple effects.

2 Likes

Could you explain what the first line does or link a resource? I’ve never seen a value be assigned in that way before

Luau types. You don’t need it at all to write code. You can read more about it here: https://luau-lang.org/

1 Like

I read about it a bit and now i understand, also is there a way to do this without creating a seperate function for each attack since every one of them is the same?

Yeah, it’s the same concept where you call task.cancel on a running thread, except you use one function.

1 Like

Alright, thanks for the huge help!

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