Getting an object through it's index in a folder

I am working on a card that requires me to select a random card through a folder of all possible cards. I thought a good way to do this way getting a random card through its index, but when I try to reference the card object through its index I get an error. What I want to figure out is how to reference an object through its index.

Here is what the output is.

4 is not a valid member of Folder "ReplicatedStorage.cardHolder"

I read some dev forum post, dev hub, and youtube to try to figure this out. The post used a very similar method to what I did but got it to work, while I can’t get mine to work. Has roblox changed the way of how indexing works?

local cards = game.ReplicatedStorage.cardHolder
while true do
	local cardIndex = math.random(1, #cards:GetChildren())
	print(cardIndex)
	local card = cards[cardIndex]:Clone()
	card.Parent = script.Parent.card
	wait(5)
	card:Destroy()
end

cardFolderGame

1 Like

Can you please provide your script and a screenshot of the cardHolder part of replicated storage?

2 Likes

My bad, I completely forgot to to that. I’ll make the edit right now

Just uploaded the script and picture of the folder. I’m sorry for not having it in the first place.

Maybe replace this with:

local cards = game.ReplicatedStorage.cardHolder:GetChildren()

The cardIndex variable you created is just a random number.
Replace this line:

local card = cards[cardIndex]:Clone()

with:

local card = cards:GetChildren()[cardIndex]:Clone()
3 Likes

Maybe try changing it to something like this:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Cards = ReplicatedStorage:WaitForChild("cardHolder")

while true do
	local RandomCard = Cards:GetChildren()[Random.new():NextInteger(1, #Cards:GetChildren())]
	RandomCard.Parent = script.Parent.card
	task.wait(5)
	RandomCard:Destroy()
	RandomCard = nil	
end

I should also add that you are trying to search the folder for the number 1, for example, even though the name of the card is “one”.
You might want to change your script a bit.

Thanks man. So what I needed is to get a list of all the cards with the getChildren() function, and then get the index of the card in that table?

I read your original post a bit wrong. The updated script I sent you should work.