- Home /
Randomly choosing 5 gameobjects?
Hello, and thanks for taking the time to read this. If I have 100 gameobjects, is there anyway to just randomly select 5 of these and then execute some code on only 5 of these randomly selected objects? For example, I randomly select gameobject, 34, 1, 78, 38 and 43, and then I can delete them, lets say. Optimally the base number 100 doesn't matter and the same code could work if there were only 50 instead or some similar situation. I don't really have any leads on this, but if someone could just steer me in the right direction in what to do that would be greatly appreciated! Thanks!
Answer by CmdrZin · Nov 23, 2020 at 12:42 AM
Just use the same method card games use to deal from the deck of cards.
1. Make a list of all the objects. Make a new empty list (pulledItems) to save the retrieved items.
2. Create a random number from 0 to size of list -1. The size of list will decrease each iteration.
3. Remove that indexed item from the list and save it into the pulledItems list.
4. Repeat steps 2 through 4 until you have your N items needed.
5. Process the pulledItems list as needed.
Look at card games for other examples.
I'm still kind of confused though, could you provide a short code example of what you mean? How do I pull out the indexed number? Thanks.
I would add that there are also data structures Stack/Heap that allow you to pick items from a collection which would save you a bunch of trouble.
Just randomise them when populating the data-structure then pop or dequeue the items as needed until empty.
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1?view=net-5.0 https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1?view=net-5.0
Thanks for the speedy reply, that was fast!
Your answer
Follow this Question
Related Questions
Random Tile Generation 0 Answers
Move Enemy randomly in a range. 3D 0 Answers
How to clone randomly 3 Answers
Make objects randomly fall 1 Answer
How to generate a random trajectory when the ball is kicked ? 1 Answer