How would I do if I wanted to spawn 5 random objects from an array, without the same object get’s chosen twice?
I’m trying to make a “find the pair” game where you need to find the 2 objects that look the same.
I already have some code that removes all other objects spawned last time, and creates a new set of items and makes 2 of the same kind, but unfortunately sometimes there are more pairs…
Don’t use a plain array, but try to use a
System.Collections.Generic.List instead. Fill it with your items just as you do this with your array, and simply remove the items from this list when you pick them.
I did this for an iOS game a while back. The process I ended up following was this:
- Create a second array you don’t mind removing pieces of, and fill it with all the cards in your deck. This includes duplicates.
- Every time you need a new card, pick a random one from the new array and REMOVE IT AFTERWARDS.
- Repeat step 2 until the array is empty, and you don’t need any more cards.
Sorry I don’t have any code for reference, but hopefully this will still help.