Use the spawn()
function.
Before we get to the point, let me explain little bits of information so you can understand how to use it.
What is a task scheduler?
A task scheduler is essentially a large loop that goes through all of the processes it has to do and executes them. It runs as fast as it possibly can, and in Lua this is a number pretty close to 0.03.
What are threads?
A thread is a group of computer instructions that can be executed by a task scheduler, in particular Lua’s thread task scheduler. In simple words, it is a block of code that runs in serial.
Multithreading is the ability to send multiple threads out to the scheduler and have it execute them simultaneously. It is an important part of parallel computing. When you create a new thread, that thread will seem to run at the same time as the rest of the code. This can be particularly useful for when you want to run processes that may take a long time, or perhaps even infinite time, side by side, such as important game loops.
Using spawn
What spawn()
does is wait for the current task scheduler update to end. Then, it puts in your request to make a new thread with some code content in it into the task scheduler and will wait until the next task scheduler update. When that update happens, the thread will execute and your code will begin executing. The content of the thread itself is the function you supply to spawn()
.
void spawn ( function callback )
It runs the specified callback function in a separate thread, without yielding the current thread.
The function will be executed the next time Roblox’s Task Scheduler runs an update cycle. This delay will take at least 29 milliseconds but can arbitrarily take longer, depending on the target framerate and various throttling conditions.
spawn()
does not return such a reference_. It’s a much more light-weight, RBX.Lua native function construct that simply queues up a new thread to the task scheduler. Once you create it, you cannot get a reference to it and you simply wait until it runs to completion.
How do I apply it to my script?
Put a spawn()
function at the start of your code. Then, create a new anonymous callback function at the first argument of the function.
After that, move your code inside the callback function.
03 | if spawnz and player.TeamColor = = BrickColor.new( "Fossil" ) then |
05 | torso.CFrame = CFrame.new(spawnz.Position + Vector 3. new( 0 , 2 , 0 )) |
07 | player.Character.Humanoid:UnequipTools() |
09 | player.Backpack:ClearAllChildren() |
13 | local sword = game.ReplicatedStorage.Weapons.Sword |
15 | sword:Clone().Parent = v.Backpack |
And your code is done! No more delays since you have applied spawn()
to it.