What is wrong with This script

There’s something wrong with this script and I don’t know what is It can you help me to know what is wrong with this script and thank you who answered.

– This script is intended to move a part up and down

local speed = 5
local height = 10
local direction = 1

while true do
    wait(0.5)
    part.Position = part.Position + Vector3.new(0, direction * speed, 0)
    if part.Position.Y >= height then
        direction = -1
    elseif part.Position.Y <= 0 then
        direction = 1
    end
end

What's wrong??
  1. Please use the correct category for your posts, which would be scripting support.
  2. Use ``` when you are posting a script, otherwise it is pretty much unreadable.

You are trying to change the variable of an active loop. You cannot do this, so your first step would be to bring your variables out of your loop, and rather than doing while true do wait(0.5) you can just do while task.wait(0.5) do

To be honest you should just use tweenservice though. Much more reliable, and way easier.

1 Like

Not bad but I recommend to use TweenService.

Also use the correct category

Here is how and example of how to use TweenService:

local part = script.Parent -- put the part here

local MaxHeight = 10
local Duration = 2 -- time to complete the movement

local easingStyle = Enum.EasingStyle.Sine
local easingDirection = Enum.EasingDirection.InOut

local function MovePart() -- the main function
	local tweenInfoUp = TweenInfo.new(Duration, easingStyle, easingDirection)
	local tweenInfoDown = TweenInfo.new(Duration, easingStyle, Enum.EasingDirection.In)

	local tweenUp = game:GetService("TweenService"):Create(part, tweenInfoUp, {Position = part.Position + Vector3.new(0, MaxHeight, 0)})
	tweenUp:Play()
	tweenUp.Completed:Wait()

	local tweenDown = game:GetService("TweenService"):Create(part, tweenInfoDown, {Position = part.Position - Vector3.new(0, MaxHeight, 0)})
	tweenDown:Play()
	tweenDown.Completed:Wait()
end

while true do
	MovePart()
end

1 Like

Thank you for telling me. I Well change it right away.

1 Like

Thank you for ALL THE help. I hope you have a good day.

1 Like

Thank you a lot. I know you put a lot of work for this script I hope you have a good day.

1 Like

“and rather than doing while true do wait(0.5) you can just do while task.wait(0.5) do”

Don’t do this, use while true do task.wait(0.5) end instead.

1 Like

Thank you for your help. And I always say have a good day

1 Like

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