Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How can I optimize this function?

function UpdateSpeed()
while true do
wait(0.1)
if plr then
local Speed = math.floor(Seat.Velocity.Magnitude)
Gui.Frame.SpeedLabel.Text = (Speed).."/"..(maxSpeed)
else
	break;
end
end
end

Having while loops to update the speed meter works, but seems to increase lag, when I remove the function the vehicle seems to move faster. Is there any alternatives to while loops that I could use to update the text of a speed meter based on the current speed of a part?

11 comments

0

.Changed

0

.Changed isn't fired on Velocity, or position

0

Neither is GetPropertyChangedSignal("Velocity")

0

You could try checking the speed every .5 seconds which would help boost preformance

0

You could also set a variable for math.floor outside of the UpdateSpeed function so you don't need to spend more time indexing.

0

Also concatenation is slow, you can try use :format with a %d%d pattern. SpeedLabel.Text = ("%d/%d"):format(Speed, maxSpeed)

0

Also set a variable outside the UpdateSpeed function for SpeedLabel so you can index it faster

0

Why not use plr as the condition for the while loop, instead of using an if? while plr do

0

good thinking @thee

1

If the speed hasn't changed by more than 0.1 for more than 2 seconds or something, decrease the frequency of polling. You get the resolution of high polling, without wasting cycles doing nothing if it's not moving, or has been moving at a constant speed for a while.

1

Alternatively, you could bind a function :GetPropertyChangedSignal("Throttle"), and only run the loop until the throttle goes back to 0.

1 answer

You can use RenderStepped that fires everytime a frame is rendered in place of the while true do loop. Example:

local function UpdateSpeed()
	if plr then
		local Speed = math.floor(Seat.Velocity.Magnitude)
		Gui.Frame.SpeedLabel.Text = (Speed).."/"..(maxSpeed)
	else
		break -- Commas are ignored by the Lua interpreter so it's not necessary to put one here
	end
end

game:GetService("RunService").RenderStepped:Connect(UpdateSpeed)

Hope this helps.

This discussion is preserved as it was. New answers, comments, and votes are closed.