When a part leaves an area it should go back to a random position

Hello,
I have a part that clones itself and moves around randomly but when it leaves a specific range it teleport’s all the parts instead of one part to a random position.

My code for spawning it

local Model = script.Parent
center = script.Parent.Center.CenterPart

local part= Model.part:Clone()

Model.ChildRemoved:connect(function()
	local newpart = part:Clone()
	local x,z = center.Position.X, center.Position.z
	local r = 10
	local x,z = math.random(x-r, x+ r),math.random(z-r,z+r)
	local pos = Vector3.new(x,center.Position.Y,z)
	
	newpart.Position = pos
	newpart.Parent = Model
end)

My code to remove the part:

local Range = Model.Configuration.partRange

while true do
	wait(5)
	if (part.Position - Model.Center.CenterPart.Position).magnitude > Range.Value then 
		part:destroy()
		break
	end
end

How many things called ‘part’ are in your workspace?

it duplicates itself 6 times and when it leaves the magnitude of center part then it should delete that part that left the center part.

So thats the issue, it has 6 parts called part.
Look in your output and I would maybe rewrite the script. When my script does not work, I rewrite it because there is most likely a small thing that you do not notice.

in my remove script i have

part = script.Parent
if (part.Position - Model.Center.CenterPart.Position).magnitude > Range.Value then 
		part:destroy()
end

This is destroys the fly but it sends the rest to a random position in the center part.
my spawn script:

local Model = script.Parent
center = script.Parent.Center.CenterPart

local part = Model.part:Clone()

Model.ChildRemoved:connect(function()
	local newpart = part:Clone()
	local x,z = center.Position.X, center.Position.z
	local r = 10
	local x,z = math.random(x-r, x+ r),math.random(z-r,z+r)
	local pos = Vector3.new(x,center.Position.Y,z)
	
	newpart.Position = pos
	newpart.Parent = Model
end)

im not sure what the issue is though

I will look into this, I may make my own post as this may concern me as this seems like someone else may wanna do it…