Issue With Part Spawning With Tables

so basically I am trying to make a thing where it spawns this block in 5 out of the 7 places.
it works, but sometimes overlaps it.

local unusedpositions = {}

local usedpositions = {}

while wait() do
for _,obj in pairs(script.Parent.SpawnZones:GetChildren()) do
    table.insert(unusedpositions,obj)
end

for i =1,#script.Parent.SpawnZones:GetChildren()-2 do
local v = math.random(#unusedpositions)
local laser = script.Parent.TallPart:Clone()
laser.Parent = workspace.MapsInGame
laser.Position = unusedpositions[v].Position
laser.Size = unusedpositions[v].Size
table.insert(usedpositions,v)
table.remove(unusedpositions,v)
end

wait(.5)
for i,v in pairs(usedpositions) do
table.remove(usedpositions,i)
end
workspace.MapsInGame:ClearAllChildren()
end

https://gyazo.com/1ffb1b038bd8ece4a80c0d10c22e0998

Here’s a few functions for you:

local function copy(from)
	return table.move(from, 1, #from, 1, table.create(#from))
end

Use copy if you want to keep your original table.

local function discard(n, from)
	local total = #from - n
	for i=1, total do
		table.remove(from, math.random(#from))
	end
	return from
end

Example usage:

while wait() do
	local positions = discard(2, script.Parent.SpawnZones:GetChildren())
	for i=1, #positions do
		local laser = script.Parent.TallPart:Clone()
		laser.Parent = workspace.MapsInGame
		laser.Position = positions[i].Position
		laser.Size = positions[i].Size
	end
end
1 Like