How do I make a function run only once

Hello, today I want to make a code of a fireball, but I want to know how I can make that when the event of damage to the user occurs, it only runs once, because when I do it runs millions of times until it disappears.

If you need the code, don’t hesitate to tell me!
Please help me, thanks!

7 Likes

I recommend learning what a debounce is and how to use it. Here is a helpful tutorial on how to use a debounce from the developer hub:

18 Likes

Alternatively, you can :Disconnect the Touched event - this allows the Garbage Collector to GC the Connected function too, freeing up memory.

For example:

local touched do --// Pushing it into a do block for clean syntax
    touched = BasePart.Touched:Connect(function()
        --// Code
        touched:Disconnect()
    end)
end

Oh, Merry Christmas too!

9 Likes

You could also use return

script.Parent.Touched:Connect(function(hit)
             ---code
              return end
end)
1 Like

That’s not going to work, the function will still be called when the event fires and they always run in a separate thread. return only stops the execution of code in the function, basically finishing the function.

Also, an end isn’t needed as there are no other blocks in the code

1 Like

That code would also prevent potential memory leaks as any connections will be prevented from being GCed until you disconnect it, or destroy the object which would ultimately result in the connections being removed.

1 Like

Return prevents reading the rest of the code, not rereading the function

2 Likes

Don’t know if this would work but if you’re using :Connect, maybe use :Once instead, I know I’m 5 years late lol, maybe this didn’t exist back then.