Will a loop lag the game if it's not major

Alright so I’m scripting a car and I needed a way of returning a value and update engine sound, my solution was to add a while wait() do loop but I stumbled upon a problem that It can cause lag, but I don’t know in this case because it updates 2 stuff.

Someone said I had to use fireallclients and update them from the client but is that really the case?

(If you know how to do this better hollar in the replies)

Generally, while wait() do can be very dangerous in terms of stability. But your script should be fine as its function is simple.

But I personally recommend RunService.HeartBeat.

2 Likes

What if there’s 5 cars running, what do you think?

Someone told me that heartbeat is worse in terms of optimization

Coroutines should be used instead of Spawn.

Just use this instead:

coroutine.wrap(function()
-- your code here
end)()
1 Like

What’s the difference, coroutines just have more abilities but other than that it’s same as spawn() no?

spawn() has a delay, it may not have much effect when the game is small, but it will add up.

1 Like

This loop shouldn’t be an issue, however, you should use task.wait() instead.
an empty task.wait() is equal to RunService.Hearbeat:Wait().
More information can be found here: Task.wait(n) vs wait(n)

You can also switch out spawn with coroutine.

coroutine.wrap(function()
   -- Code.
end)()

Coroutine vs. spawn:

1 Like

Like @coolalex1835 said, you could use the Heartbeat event of RunService or you could do this:

seat:GetPropertyChangedSignal("Velocity"):Connect(function()
     local mag = seat.Velocity.Magnitude
     script.MPH.Value = mag
     script.Parent.MainTing.CarTingYe.Engine.PlaybackSpeed = 1 + mag / seat.Torque
end)
1 Like

I don’t know man doesn’t seem to work

Learning more about them, thank you

(Still not sure if it keeps lag away but we’ll see)

1 Like

Just incase you were confused, I will explain the 2 major things I brought up.

Coroutines create a thread, basically like a script. Running anything in a corountine would be run like if it was on a different script. Which is useful for multi-tasking scripts.

RunService.HeartBeat fires every frame after the physic simulation has been done. If you want to have it fire before the physic simulation then I suggest RunService.Stepped.

1 Like

I don’t see any issues with my code, unless I’m going insane from sleep deprivation.

2 Likes