How to tween a part to many different positions with one line

Is there a better way to write this script out? A more professional way? So I can make the part move to these locations without having to write out each tween separately?

local TS = game:GetService("TweenService")
local TI = TweenInfo.new(1, Enum.EasingStyle.Linear)

local Tweens = workspace.TweenLocations

local Part = script.Parent


local Tween1 = TS:Create(Part, TI, {CFrame = Tweens.Location1.CFrame})
local Tween2 = TS:Create(Part, TI, {CFrame = Tweens.Location2.CFrame})
local Tween3 = TS:Create(Part, TI, {CFrame = Tweens.Location3.CFrame})
local Tween4 = TS:Create(Part, TI, {CFrame = Tweens.Location4.CFrame})
local Tween5 = TS:Create(Part, TI, {CFrame = Tweens.Location5.CFrame})


task.wait(5)

Tween1:Play()
Tween1.Completed:Wait()

Tween2:Play()
Tween2.Completed:Wait()

Tween3:Play()
Tween3.Completed:Wait()

Tween4:Play()
Tween4.Completed:Wait()

Tween5:Play()
Tween5.Completed:Wait()
task.wait(5)

for _, v in ipairs(Tweens:GetChildren()) do
     local t = TS:Create(Part, TI, {CFrame = v.CFrame})
     t:Play()
     t.Completed:Wait()
end

Use a loop.

Edit: It’s probably better to use tables for locations anyway instead of instances:

local locations = {
   CFrame.new(),
}

--(...)
for _, cf in ipairs(locations) do
--(...)
 {CFrame = cf})
--(...)
1 Like

Everyone has their own way of doing it, but here’s how I would approach it:

I would create a module responsible for generating the tweens and returning a function to play them. This way, all I need to do is pass the folder containing the target positions and the part I want to move.

Module:

local TS = game:GetService("TweenService")

return function(folder: Folder, tweenInfo, part: Part)
    local tweens = {}

    for i = 1, #folder:GetChildren() do
        local locationName = "Location" .. i
        local location = folder:FindFirstChild(locationName)
        if location then
            table.insert(tweens, TS:Create(part, tweenInfo, {CFrame = location.CFrame}))
        end
    end

    local function play()
        for _, tween in tweens do
            tween:Play()
            tween.Completed:Wait()
        end
    end

    return play
end

Script:

local TI = TweenInfo.new(1, Enum.EasingStyle.Linear)
local Tweens = workspace.TweenLocations
local Part = script.Parent

local Module = require(script.Module)

local play = Module(Tweens, TI, Part)

task.wait(5)

play()
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.