How to put a wait() that doesn’t stop the script

I would like it so that there is a gun that shoots a projectile, then waits until it reaches its target to destroy. I found that waiting for the bullet to destroy will also make the gun wait to shoot again. How can I make it so that putting a wait in a function will not cause the entire script to wait?

4 Likes

I dont understand ur question. Cause you want the gun to stop firing until the projectile reach the target and destroy, in order to shoot another projectile, but at the same u want a second projectile to be shoot before the first projectile reach the target :v

just do a cool down of 2-5 seconds
edit: or tool.enabled is false and when the projectile hit its target, tool.enabled is true

Use spawn. This will ‘spawn’ the function and will not require it to finish before continuing.

spawn(function()
 --CODE HERE
end)
1 Like

With spawn you will wait at least ~1/30th of a second because of the legacy task scheduler and you can’t even guarantee your code will ever even run. Explicitly using coroutines would be better here.

coroutine.wrap(function()
    -- code
end)()
5 Likes

To run code while letting the main script continue, you can use threading, which on roblox, can be incorporated by developers mainly though coroutines as others have mentioned.

However, I think a much more efficient option in this case would be to use roblox’s built in service Debris. It allows roblox to handle objects that need to be destroyed after a certain amount of time, without holding up your main script at all.

Example:

Debris = game:GetService("Debris")

Debris:AddItem(Bullet, 5) --bullet will be destroyed in 5 seconds
8 Likes