I am working on a game about creating and driving Space ships, and I am making a slider that manages throttle. It works, but the throttle value sometimes freezes and I cannot find a way to improve it.
The code
local uis = game:GetService("UserInputService")
uis.InputChanged:Connect(function(input, gameProccessedEvent)
if uis:IsKeyDown(Enum.KeyCode.LeftShift) or uis:IsKeyDown(Enum.KeyCode.RightShift) then
if uis:IsKeyDown(Enum.KeyCode.LeftControl) or uis:IsKeyDown(Enum.KeyCode.RightControl) then
while uis:IsKeyDown(Enum.KeyCode.W) or uis:IsKeyDown(Enum.KeyCode.Up) do
if script.Parent.SliderValue.Value <= 99 then
script.Parent.SliderValue.Value += 1
script.Parent.TextLabel.Text = "Throttle: "..script.Parent.SliderValue.Value.."%"
script.Parent.Slider.Position = UDim2.new(0.5, 0, script.Parent.SliderValue.Value / 100, 0)
end
wait(0.25)
end
while uis:IsKeyDown(Enum.KeyCode.S) or uis:IsKeyDown(Enum.KeyCode.Down) do
if script.Parent.SliderValue.Value >= 1 then
script.Parent.SliderValue.Value -= 1
script.Parent.TextLabel.Text = "Throttle: "..script.Parent.SliderValue.Value.."%"
script.Parent.Slider.Position = UDim2.new(0.5, 0, script.Parent.SliderValue.Value / 100, 0)
end
wait(0.25)
end
end
end
end)
I believe it could be something about the delays I placed or because of a thing I have been doing inefficiently, but if you have any questions or feedback, feel free to reply.
Don’t use while loops in connections. Busy waiting in an event isn’t smart.
Anyways, try this:
local uis = game:GetService("UserInputService")
local rs = game:GetService("RunService")
local Last = os.clock()
local AdjustSpeed = 0.25
local Processed = true
local Object = script.Parent
local SValue = Object.SliderValue
local Label = Object.TextLabel
local Slider = Object.Slider
uis.InputChanged:Connect(function(input, gameProccessedEvent)
Processed = gameProccessedEvent
end)
local Handler = rs.Heartbeat:Connect(function(Step)
if Processed then return end
if os.clock()-Last < AdjustSpeed then return end
if uis:IsKeyDown(Enum.KeyCode.LeftShift) or uis:IsKeyDown(Enum.KeyCode.RightShift) then
if uis:IsKeyDown(Enum.KeyCode.LeftControl) or uis:IsKeyDown(Enum.KeyCode.RightControl) then
if uis:IsKeyDown(Enum.KeyCode.W) or uis:IsKeyDown(Enum.KeyCode.Up) then
if SValue.Value <= 99 then
SValue.Value += 1
Label.Text = "Throttle: "..SValue.Value.."%"
Slider.Position = UDim2.new(0.5, 0, SValue.Value / 100, 0)
end
Last = os.clock()
elseif uis:IsKeyDown(Enum.KeyCode.S) or uis:IsKeyDown(Enum.KeyCode.Down) then
if SValue.Value >= 1 then
SValue.Value -= 1
Label.Text = "Throttle: "..SValue.Value.."%"
Slider.Position = UDim2.new(0.5, 0, SValue.Value / 100, 0)
end
Last = os.clock()
end
end
end
end)