Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

While loop causing lag, not sure how to fix?

Asked by 4 years ago

I have a script which rotates the camera around the lobby when the player first loads in, when they click a GUI button 'play' the color correction of the world changes from heavily red to a normal white color.

When testing the game there is no lag when 'play' is clicked, the color correction fades from red to white and then the camera is centred on the player like normal. However if the script is left to run for a minute and 'play' is clicked there is massive lag and the color correction fade takes a while to return to normal with a stuterring effect of the camera rotation.

I know the problem is to do with the while loop and the rotation of the camera because when I removed the while loop and the camera rotation there was no problem with the color correction fade no matter how long the script had been running.

I am really at a loss of how to fix this and would appreciate any help! Thanks

while InMenu do
    wait()
    camera.CoordinateFrame = CFrame.new(target.Position)  --Start at the position of the part
    * CFrame.Angles(0, angle, 0) --Rotate by the angle
    * CFrame.new(0, 5, 35)       --Move the camera backwards 5 units
    --camera.Focus = CFrame.new(target.Position)
    angle = angle + math.rad(0.2) --Change this for rotational speed


    StartButton.MouseButton1Click:Connect(function() --When the user presses the play   button
        MenuPlayMusic:Play()
        MenuGUI.Visible = false --Hides the main menu GUI
        for i = 0,1,0.01 do
            MenuColorCorrection.TintColor = Color3.new(1, i, i) 
            wait()
        end

        InMenu = false
        camera.CameraSubject=player.Character.Humanoid
        camera.CameraType = "Follow"
end

1 answer

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

It looks like you're assigning a function to an event listener (MouseButton1Click in StartButton) on every iteration of the loop. If I'm not mistaken, then each time you assign a function to the event listener, it stays there even if you assign another on top of it! So, when you click the button, every one of those assigned functions gets called, which means hundreds or even thousands of loops get created from one click, and it will severely lag the server.

The solution to your problem is to assign that function before (but not after) the while loop. Alternatively, you can handle that in a different script, most easily placed under the button itself in the GUI hierarchy.

0
Thanks that's fixed it, and what you wrote makes sense. I didn't realise that the function would still work outside of the loop which is why I put it inside the while loop, but anyway thanks for the quick response! RIBBENTROPP 45 — 4y
Ad

Answer this question