x


Shuffle objects in object array randomly in C#

Hello,

I'm new to Unity. I'm developing a card game and could use a little help shuffling the deck without looping through the array(s) more times than necessary.

(using C#) I have this object array populated with my "Card" prefab objects:

int totalCards =  numberOfDecks * numberOfCardsPerDeck;
object[] aShoe = new object[totalCards];

Assuming aShoe is populated with objects, how can I return aShoe (randomly) shuffled (plz)?

aShuffled = ???
//then...
object[] aShoe = aShuffled;

~Chance

P.S. Note: Any random will do and thanx in advance.

more ▼

asked May 15 '12 at 04:22 PM

ChanceTouchstone gravatar image

ChanceTouchstone
17 1 1 3

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

The "Inside-Out" algorithm listed here should work nicely: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

Alternatively, for a pre-coded C# method, try this (it's a bit less efficient though): http://www.dotnetperls.com/shuffle

more ▼

answered May 15 '12 at 04:35 PM

Rob Fireproof gravatar image

Rob Fireproof
66 1 3

That is the best answer. However, now I think I would prefer to use implement this using an ArrayList instead of an object array because of the .Add() .Remove() methods (despite any inefficiency on this small project). But when I try to reference one of my Prefab objects in the ArrayList i get an error:

foreach(Card c in alShoe) { c.renderer.enabled = true; //or //c.SendMessage("FlipCard");

}

Error: InvalidCastException: Cannot cast from source type to destination type.

May 15 '12 at 08:30 PM ChanceTouchstone

Nevermind, I got it. I had to cast it as a Rigidbody rather than my prefab.=)

May 15 '12 at 09:10 PM ChanceTouchstone

@chancetouchstone: Don't post answers if it doesn't answer the question. Use comments.

Also don't use an ArrayList. Just use a generic List. You need the System.Collections.Generic namespace then you can define your list like this:

List<Card> myCardList = new List<Card>();

The list class has almost the same functions as the ArrayList class, but is strongly typed, so accessing a member of the list will return a Card-reference. I guess "Card" is a custom script of yours that is attached to the prefab...

May 15 '12 at 09:23 PM Bunny83

Yeah that was much cleaner. Thanx

May 23 '12 at 01:47 PM ChanceTouchstone
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4140
x571
x9
x7
x1

asked: May 15 '12 at 04:22 PM

Seen: 1510 times

Last Updated: May 23 '12 at 01:47 PM