Prevent math.random from getting the same thing over again

I want to clone 8 models and put its primary part’s CFrame at another random parts CFrame using math.random. The only issue is that it uses the same random part CFrame over and over again. I’ve tried looking everywhere but I can’t find a solution.

	local getChildren = workspace.Crystals["Possible Locations"]:GetChildren()

	for i = 1,8 do
		local modelClone = game:GetService("ReplicatedStorage"):WaitForChild("Crystal"):Clone()					
		local randomPart = getChildren[math.random(#getChildren)]
		
		modelClone.PrimaryPart.CFrame = randomPart.CFrame
		modelClone.Parent = workspace.Crystals
	end

You can use the Random library:

local getChildren = workspace.Crystals["Possible Locations"]:GetChildren()
local random = Random.new() -- create a new 'Random' object using the constructor

for i = 1,8 do
   local modelClone = game:GetService("ReplicatedStorage"):WaitForChild("Crystal"):Clone()					
   local randomPart = getChildren[random:NextInteger(1, #getChildren)] -- get a random object from the integer
		
   modelClone.PrimaryPart.CFrame = randomPart.CFrame
   modelClone.Parent = workspace.Crystals
end

Or use the solutions below

Make a table of values that math.random already got.

Is your issue that you want each random number to be used only once? You could try using a table:

this will only work if you have 8+ random locations
LMK IF IT BREAKS

local getChildren = workspace.Crystals["Possible Locations"]:GetChildren()

local ew = {}
for i,v in pairs(getChildren) do
	table.insert(ew, #ew+1)
end
local function shuffle(t)
	local j, temp
	for i = #t, 1, -1 do
		j = math.random(i)
		temp = t[i]
		t[i] = t[j]
		t[j] = temp
	end
end
shuffle(ew)

for i = 1,8 do
	local modelClone = game:GetService("ReplicatedStorage"):WaitForChild("Crystal"):Clone()					
	local randomPart = getChildren[ew[i]] -- get a random object from the integer
	modelClone.PrimaryPart.CFrame = randomPart.CFrame
	modelClone.Parent = workspace.Crystals
end

I already said that- :skull:
Don’t post duplicate responses

Your response was not much better.

image

And my method works just fine

Alright well I did not ask for your opinion.

I didn’t ask for you to comment on what I said with my shuffle table method either. This is the developer forum, not the “phyouthcenter1 must ask for your input before you post forum”

This code works, I think. tsym :skull:

1 Like

I know its solved but fix for true math.random use math.randomseed

math.randomseed(tick())
math.random(1,2)

this is how i do it

local children = workspace.Crystals["Possible Locations"]:GetChildren()
local selected = {}

for i = 1, 8 do
	table.insert(selected, table.remove(children, math.random(#children)))
end

for i, value in ipairs(selected) do
	print(i, value)
end

You could’ve put more effort into your post, but you’ve posted ONE sentence. And you are saying @alessdai made a duplicate response? Just know, people like you are not welcome here.