Math.random Keeps getting the same instance

Hi. My math.random keeps getting the same instance every time the function is called.

game.ReplicatedStorage.Events.DrawACard.OnClientEvent:Connect(function(Card)
	local Confirmed = false
	game.ReplicatedStorage.Events.DrawACard:FireServer() --Sort of sending info that the round is over
	for i, v in pairs(Cards:GetDescendants()) do
		if v:IsA("ImageButton") then
			
			local PossibleDraws = {}
			local Owned = v:FindFirstChild("Ownership")

			if Owned.Value == true then
				--print(v.Name)
				table.insert(PossibleDraws, v)
				
				--[[
				for _, i in pairs(PossibleDraws) do
					print(i)
				end
				]]
				
				local CardSelected = PossibleDraws[math.random(1, #PossibleDraws)]
				if CardSelected and Confirmed == false then
					Confirmed = true
					game.SoundService.GUISounds.CardDraw:Play()
					local NewCard = CardSelected:Clone()
					NewCard.Parent = Deck
				end
				
			else
				--print(v.Name, " is not owned.")
			end			
			
		end
	end
end)

No errors are showing up, and there is more than one instance in the PossibleDraws table (which i double checked by doing the for _, i in pairs) No idea why this is happening though. Any help is appreciated.

Some things you can try:

  1. Check to make sure that the instances in the PossibleDraws array are not just the same instance repeating
  2. Try using Random.new() instead of math.random
  3. Check other parts of the codebase to see if it’s conflicting with your card selecting process after it has selected a card
1 Like

Take out the -- before all the print statements so they actually help you troubleshoot.
They’ll let you know what sections of code are running and which ones aren’t.

Without testing anything here it looks like for next loop is out of place and local PossibleDraws = {} is out of place. PossibleDraws should be created, then after loadded up in the for next, then a random card is picked. All this should be after eachother not all in the same for next loop I would think …

As is it looks like you’re getting the last possible pick from a new pool of 1 card.

it happened to me before i changed the location some codes and it worked

you have to select the card after possible draws is filled, right now it’s adding a valid card to possible draws then immediately selecting that same card

Turns out it was because this block

local CardSelected = PossibleDraws[math.random(1, #PossibleDraws)]
				if CardSelected and Confirmed == false then
					Confirmed = true
					game.SoundService.GUISounds.CardDraw:Play()
					local NewCard = CardSelected:Clone()
					NewCard.Parent = Deck
				end

was inside the “If Owned.Value == true then” function. Thanks for everyone who replied though :slight_smile:

1 Like

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