I am currently trying to make a whole model of parts rotate on the X axis 30 degrees, and then rotate the other direction when it hits 30 degrees with one click of a button. What’s weird is the script works when I remove the while true do part, but when I add it, it does not. What do you think?
local model = game.Workspace.Stampede
local rotate = game.Workspace.Stampede.PPA.Orientation.X
local rad = math.rad
local rotateAmount = 1
local unrotateAmount = -1
local clickDetector = script.Parent.ClickDetector
function OnClick()
while true do
if rotate == 0 then
local newCFrame = model.PrimaryPart.CFrame * CFrame.Angles(rad(unrotateAmount), 0, 0)
model:SetPrimaryPartCFrame(newCFrame)
if rotate == 30 then
local newCFrame = model.PrimaryPart.CFrame * CFrame.Angles(rad(rotateAmount), 0, 0)
model:SetPrimaryPartCFrame(newCFrame)
end
end
end
clickDetector.MouseClick:Connect(OnClick)
end
You should probably try breaking that “while true do” loop (because it seems it just gets stuck in that loop), or maybe do a “repeat until” loop instead.
Firstly, indent your code so you can see what the structure actually is and what each ‘end’ is closing.
Next problem is the connection of the OnClick function being inside the OnClick function. Move it to after the last ‘end’ that ends the OnClick function.
Lastly, the while true do is an infinite loop, and every click will spawn a new running copy of said loop, all trying to adjust the same model. Probably not what you want.
A general rule of thumb is to never make while true do loops that have no way to exit (a logically-reachable break or return statement). If you find yourself wanting a while loop to run forever, and you’ve already got yielding functions inside making sure it isn’t just going to lock up the thread, you should still probably be binding to an event like Heartbeat instead. If a while true do loop exits due to some code inside throwing an error, it won’t recover and keep looping (classic cause of “dead servers” due to game loop being a while true loop).
I actually found out a different way to script this. I didn’t need to use the orientation at all.
local model = script.Parent
local box = script.Parent.PrimaryPart
local clickDetector = game.Workspace.Button.ClickDetector
function onClick()
wait(2)
for i = 1, 30 do
local newCFrame = box.CFrame * CFrame.Angles(0, 0, math.rad(1))
wait(0.1)
model:SetPrimaryPartCFrame(newCFrame)
end
while true do
for i = 1, 60 do
local newCFrame = box.CFrame * CFrame.Angles(0, 0, math.rad(1)):Inverse()
wait(0.1)
model:SetPrimaryPartCFrame(newCFrame)
end
wait (2)
for i = 1, 60 do
local newCFrame = box.CFrame * CFrame.Angles(0, 0, math.rad(1))
wait(0.1)
model:SetPrimaryPartCFrame(newCFrame)
end
end
clickDetector.MouseClick:Connect(onClick)
end
This is also indented, but for some reason it does not indent when sent.