How to detect if a for loop ends (solved)

Alright, so I’m trying to destroy a semi when it reaches the end point. I have the for loop that makes the semi move, but I’m trying to figure out how to check when the for loop ends.

Code I tried:

wait(0.8)
for i = 0.001,1,0.001 do
local lerpPos = script.Parent.PrimaryPart.CFrame:Lerp(workspace.Part.CFrame,i)
script.Parent:SetPrimaryPartCFrame(lerpPos)
task.wait(0.05)
end
print(‘this is after the loop ended’)

2 Likes

when the loop ends, it’ll go onto everything after the end. Add a line after the end and make it so it destroys the part by doing:

wait(0.8)
for i = 0.001,1,0.001 do
local lerpPos = script.Parent.PrimaryPart.CFrame:Lerp(workspace.Part.CFrame,i)
script.Parent:SetPrimaryPartCFrame(lerpPos)
task.wait(0.05)
end
print(‘this is after the loop ended’)
script.Parent:Destroy()
1 Like

Well, I’ve already tried this. It doesn’t print anything or destroy anything

1 Like

because it’ll go on for a long time since it waits 0.05. And it’ll repeat for a while since its starting on 0.001 and increasing by 0.001 Do. Should fix it. Make sure to add the part I put above. after the loop

for i = 0.1,1,0.1 do
local lerpPos = script.Parent.PrimaryPart.CFrame:Lerp(workspace.Part.CFrame,i)
script.Parent:SetPrimaryPartCFrame(lerpPos)
task.wait(0.05)
end
1 Like
wait(0.8)
for i = 0.001,1,0.001 do
    local lerpPos = script.Parent.PrimaryPart.CFrame:Lerp(workspace.Part.CFrame,i)
    script.Parent:SetPrimaryPartCFrame(lerpPos)
    task.wait(0.05)
end
print("this is after the loop ended")

Since you’re looping it 1000 times and a wait 0.05 in between you gotta wait 50 seconds before it prints anything at all

2 Likes

Well, this made the script print the statement. Now the semi just flies across the road.

1 Like

Consider using tween service instead. Way better than lerps.

1 Like

Sure, how would I tween a whole model?

1 Like

Actually, i’ll figure it out myself. Thanks for the responses!

1 Like

I just wrote a script to tween the model. Do you still want it?

1 Like

Oh sure, I was researching it but yeah.

1 Like

Ok, first. Unanchor everything other than the primary part. next weld everything to the primary part. After that, insert this script into the model. Edit it to your liking:

local TS = game:GetService("TweenService")
local Goals = {
	CFrame = CFrame.new(workspace.Endpoint.Position)
}
local Info = TweenInfo.new(10)
local Model = script.Parent
local Tween = TS:Create(Model.PrimaryPart, Info, Goals)
Tween:Play() -- starts
Tween.Completed:Connect(function() -- after its done
	Model:Destroy()
end)
3 Likes

This worked, thank you so much!

1 Like

How does the accepted answer relate to the main question “How to detect if a for loop ends” ? You should change the title

1 Like