How to limit the amount of copying of an object in a function

My problem is that I don’t know how to control the amount of copying of an object in a function. Because I use several loops, my code is also not very optimized, which is also a problem.

local function createObject()
	for _,object in pairs(objects:GetChildren()) do
		if object:IsA("Model") and object.Name==objectName then
			local newObject=object:Clone()
			newObject.Parent=folder
			return newObject
		end
	end
end

local width=100
local height=50
local offset=5

local function spawnObject(x,y)
	print("Spawning at position: (" ..x.. ", " ..y.. ")")
	local object=createObject()
	if object then
		object:SetPrimaryPartCFrame(CFrame.new(x,y,0))
	end
end

for x=offset-width,offset do
	for y=offset-height,offset do
		spawnObject(x,y)
	end
end

players.PlayerAdded:Connect(spawnObject)
1 Like

Could you more closely explain what you mean with “control the amount of copying”. I might be able to help you after that

1 Like

Script spawns too many objects because of the cycles, but I need to control this amount. For example, I want the object to be cloned only 10 times.

1 Like

I see. The problem is the for loop. What do you need that one for?

1 Like

I use it to calculate the area of ​​an object and spawn objects on it.

1 Like

You could limit the objects this way, just know that the approach you are using is VERY inefficient. I changed some things to make it at least a little more efficient but it will still lag your game at some point because your way makes way to many parts.

local testObject = game.ReplicatedStorage.testModel

local function createObject()

local newObject = testObject:Clone()
newObject.Parent = folder
return newObject
end

local width=100
local height=50
local offset=5
local maxObjects = 200000

local currentObjects = 0

local function spawnObject(x,y)
print(“Spawning at position: (” …x… ", " …y… “)”)
local object = createObject()

currentObjects = currentObjects + 1
if object then
	object:SetPrimaryPartCFrame(CFrame.new(x,y,0))
    end
end

for x = offset - width, offset do

if currentObjects < maxObjects then
	for y = offset - height,offset do
		if currentObjects < maxObjects then
			
			spawnObject(x,y)
			
			--task.wait()
		end
	end
end
--task.wait()

end
players.PlayerAdded:Connect(spawnObject)

Idk. why parts of the script aren’t highlighted but the script should still be readable lol

2 Likes

Thanks, but I’ve already fixed that.

1 Like

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