How to stop my script from running when a condition is met?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    Why won’t this stop? I’m using a if check to find a value and if it does I want the whole function to stop and not run, however, even though the check finds a value it still runs the rest of the code.
local selectables = game.Workspace:WaitForChild("Selectable")
local rs = game:GetService("ReplicatedStorage")
local selectables_recovery = rs:WaitForChild("Selectable_Recov_Modern")

selectables.DescendantRemoving:Connect(function(descendant)
	if descendant:isA("BasePart") or descendant:isA("MeshPart") then

		if descendant:FindFirstChild("ThisIsItem") then
			print("STOPPING EVERYTHING SINCE THIS IS FOOD OR ITEM, DO NOT RUN REST")
		end

		local posvector = descendant:FindFirstChild("DefaultPositionValue").Value
		local orientationvector = descendant:FindFirstChild("DefaultOrientationValue").Value
		local descendant_name = descendant.Name

		descendant.Parent:Destroy()

		for i,v in pairs(selectables_recovery:GetDescendants()) do
			if v.Name == descendant_name then
				find_recovery_part = v
			end
		end
		local recoverymodel = find_recovery_part.Parent

		if find_recovery_part and recoverymodel then
			local recoveryclone = recoverymodel:Clone()
			recoveryclone.Parent = selectables
		else
			warn("Can't find it")
		end
	end
end)

Use someting called “return”.

Type it after the place you want the script to stop itsself.

1 Like

Forgot to mention in my code i do have a “return” after the print with the big caps and stuff but still the code runs.

return stops the code in a function from running
using it outside of a function will cause the entire script to stop running

continue inside of a loop makes it skip one loop and go to the next

break inside of a loop makes the entire loop stop running

1 Like

How could I place a return so that when the “ThisIsItem” check is true it stops?

if descendant:FindFirstChild("ThisIsItem") then
  print("stopped script")
  return
end

check to make sure it is printing

I did exactly that and it does print but then I get an error on a line after that with an error since the food / item does not contain defaultpositionvalue etc… so despite the return it still runs. And I’ve made sure the descdendant only has 1 part that is a BasePart or MeshPart so it only iterates once.

return will always stop the script from running

try adding a print at the top after this line to see how many times its running
selectables.DescendantRemoving:Connect(function(descendant)

Thank you, when I wrote that I checked every part I realized I had made some small changes to it that caused it to run a few times for a part that does not have the value, fixed it. Top g.

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