Script Only Running Once!

I have a script that checks to see if a weld is inside a part. I’m using FindFirstChild() to check and it, but it doesn’t loop around to check again. When I use WaitForChild() it works fine but doesn’t do the second part of the script. I’m wondering if there is any way to loop through to check if it is there?

  • This is the script
local Bar = script.Parent.Parent.Parent.Bar.Attach
local Weld = Bar:FindFirstChild("Weld")

function Out()
	while script.Parent.Length < 10 and Bar:FindFirstChild("Weld") do
		script.Parent.Length = script.Parent.Length + 0.1
		wait(0.2)
	end
end

function In()
	while script.Parent.Length > 1 do
		script.Parent.Length = script.Parent.Length - 0.1
		wait(0.1)
	end
end

if Weld then
	if script.Parent.Length < 10 then
		Out()
	end
else
	In()
end	

Any help would be appreciated!

1 Like

This script is going to only run once because you put an if statement, put a function or loop instead.

I tested it in studio, and the functions work perfectly for me. Do you want the if Weld then part to loop?

It has to be recursive function use this:

Bar:FindFirstChild("Weld", true)

maybe you should do something like

function Out()
coroutine.wrap(function()
	while script.Parent.Length < 10 and Bar:FindFirstChild("Weld") do
		script.Parent.Length = script.Parent.Length + 0.1
		wait(0.2)
	end
end)()
end

so it doesnt yeild

local Part = script.Parent
local Bar = Part.Parent.Parent.Bar.Attach --try to avoid referencing instances like this
local Weld = Bar:FindFirstChild("Weld")

local function Out()
	while Part.Length < 10 do
		if not Bar:FindFirstChild("Weld") then
			return
		end
		Part.Length += 1
		task.wait(0.2)
	end
end

local function In()
	while Part.Length > 1 do
		Part.Length -= 1
		task.wait(0.1)
	end
end

while task.wait(0.5) do
	if Weld then
		if Part.Length < 10 then
			Out()
		end
	else
		In()
	end
end

If you need functions to run multiple times then you need to call them multiple times (you can achieve this by creating a loop in which the functions are called). Remember that you can declare functions locally. The wait() calls should be replaced with task.wait() as it is more accurate and x = x - y is the same as x -= y. Also instead of repeating “script.Parent” create a reference for the script’s parent (which is shorter and cleaner) in the above code I’ve used “Part”.

I fixed it by using ChildAdded and ChildRemoved. Thanks for all the help!