My I = 1,3 loop repeats numbers only on 1 and 3

Hey guys,

In this script I am trying to get 3 random parts(tools) from a folder. The issue I’ve been coming into is that 1 and 3 can still be the same item, despite having set up logic.
image

The logic I have setup right now, from the looks of it only checks 1 and 2 to make sure they’re not the same, but 3 can be the same as 1 in rare circumstances.

The loop in question is the i = 1,3 do loop, I’ve tried adding a new variable of MiddleIndex, but it didnt work for me.

local debounce = false
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local EligibleItems = ReplicatedStorage.PossibleItems:GetChildren()

local count = 0
for _,v in pairs(EligibleItems) do 
	count = count + 1
end



script.Parent.ClickDetector.MouseClick:Connect(function(hit)
	if debounce == false then
		
		debounce = true
		hit.Team = game.Teams.Blue
		
		local lastIndex = 0
		local Index = count
		
		for i = 1,3 do 
			
			repeat
				Index = math.random(1,count)
				
			until Index ~= lastIndex 
			lastIndex = Index
			
			
			local RandomChild = ReplicatedStorage.PossibleItems:GetChildren()[Index]
			local ClonedForInv = RandomChild:Clone()
			print(ClonedForInv)

		end

		print("\n")
		wait(0.5)
		debounce = false

	end
end)

What you could do is have a table variable to check for used indexes rather than a variable as it’s able to hold more than one index that you already used

local usedIndexes = {}

-- In your for loop

repeat
-- random index code
until not table.find(usedIndexes, index)

table.insert(usedIndexes, index)

-- Rest of your code
1 Like

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