Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I allow a loop to continue after it has completed a task?

So i'm trying to make a tree vanish after it's been hit 5 times. That bit works.

However, after it goes invisible; and then becomes visible again, the loop doesn't continue. As in, when it gets to 5 again, it does nothing...

Any ideas?

while script.Parent.Damage.Value <5 do
	wait()
end

if script.Parent.Damage.Value >= 5 then
	script.Parent.Name = "Gone"
	local descendants = script.Parent:GetDescendants()
for index, descendant in pairs(descendants) do
	if descendant:IsA("BasePart") then
		descendant.Transparency = 1
		descendant.CanCollide = false
	end
	
end
wait(10)
	local descendants2 = script.Parent:GetDescendants()
for index, boo in pairs(descendants2) do
	if boo:IsA("BasePart") then
		boo.Transparency = 0
		boo.CanCollide = true
		end
	end
	script.Parent.Name = "Tree"
	script.Parent.Damage.Value = 0
end

Thank you.

1 comment

1

You should be using events not loops for this work

1 answer

Well, first of all, this script isn't very efficient, but that's besides the point.

If you want to loop this over and over again, the simplest thing you would do is wrap all of this in another while true loop like so:

while true do wait()
	-- PASTE YOUR CODE HERE
end

You can simply just paste your code here and it should work perfectly fine. Additionally you can replace the first while loop that runs while the value is less than 5 with a repeat until loop.

However, the most efficient and lag-free way of doing something like this would be to make the function fire when the value is changed. It would be something like so:

function Tree(value)
	if value >= 5 then
		-- you would paste everything after line 4 here.
	end
end

script.Parent.Damage.Changed:Connect(Tree)

I haven't checked this in studio so I might have done something wrong, but anyways; what this does is fire the function that removes and regenerates the tree every time the value reaches 5. This way you don't need to run a while loop, which can lag the game if you have multiple trees, and is just a bad idea of solving this. This is far more efficient. The .Changed event will fire every time the value changes, however because we did if value >= 5 then it will run the remove and regen part of the function when it reaches 5. We don't need to do >= more or equal to in this case, but its a good idea just in case the value somehow surpasses 5. Also you don't need two local descendants =, one will do just fine since the descendants of the tree haven't changed (none were removed or new ones added, at least im assuming).

hope this helped!! :DD sorry if it was a little confusing ghhh but i hope i helped you!

This discussion is preserved as it was. New answers, comments, and votes are closed.