A problem with region3!

I need help with a automatic destroying feature! So i have random Object generators which sometimes position the models somewhere where i dont want them to be! So i made a region3 script which basically gets the parts inside the region and looks for the parents name either being “Rock” or “Tree” … These are my objects… To get to my problem:

The script down below gives out an error after the model has been deleted, after that doesnt work anymore… So now my question: "How can i make sure that the script always runs without breaking when a model is deleted!

Thanks you for you help!

local RegionPart = workspace.Destroyer
local Pos1 = RegionPart.Position - (RegionPart.Size / 2)
local Pos2 = RegionPart.Position + (RegionPart.Size / 2)
local Region = Region3.new(Pos1,Pos2)
RegionPart:Destroy()

while true do
	wait(1)
	local PartsInRegion = workspace:FindPartsInRegion3(Region,nil,100000000000)
	for i, part in pairs(PartsInRegion) do
		
		if part.Parent.Name == "Tree" or part.Parent.Name == "Rock" and part.Parent.Name == not nil then
			print(part.Parent)
			part.Parent:Destroy()
		end
		
	end
	
	
end

You haven’t sent the error in the console, showing us a script with no error log makes it very hard to debug code

1 Like

Verify that the part has a parent before checking the parent’s name.

local parent = part.Parent
if parent then
  if parent.Name == "Tree" then
    ...
  end
end
2 Likes