# Looping If Function? Maybe?

I am creating a game with cards that randomize as soon as the level starts but I’m running into dead ends on my code.

``````#pragma strict
var objects : GameObject[];
var cards : Transform[];
var positions : Transform[];
private var first : boolean = true;
private var num : int;

function Start () {
Randomize();
}

function Randomize () {
for(var position in positions){
//Desired return point
yield StartCoroutine("Assign");
if(cards[num] != null){
Instantiate(cards[num], position.position, position.rotation);
cards[num] = null;
}else{
// Need it to return here
}
}
}

function Assign () {
num = Random.Range(0, cards.length);
}
``````

The same wall that stops me is that I need to loop if my conditions doesn’t meet. Or can anyone find any other way. I could just loop it again but it could become endless if I keep doing that and there would be a stack overflow.

First of all, why do use Assign as a coroutine?

The problem is, that its possible that he choses the same number repeatedly.
You should assign ‘cards’ to a list and use the list instead.

The best way would be to shuffle the array of cards, then just insert them one by one.

This is C# but could be converted to JS:

``````public void ShuffleCards(Transform[] obj)
{
for (int i = 0; i < obj.Length; i++)
{
Transform temp = obj[i];
int obj_index = Random.Range(0, obj.Length);
obj[i] = obj[obj_index];
obj[obj_index] = temp;
}
}
``````

i think this is it in JS:

``````function ShuffleCards(obj : Transform[])
{
for (var i : int = 0; i < obj.length; i++)
{
var temp : Transform = obj[i];
obj_index : int = Random.Range(0, obj.length);
obj[i] = obj[obj_index];
obj[obj_index] = temp;
}
}
``````

Then in Start, call

``````ShuffleCards(cards);
Randomize();
``````

this should work:

``````function Randomize () {
var i : int = 0;
for(var position in positions){
i++;
if (cards[i] != null){
Instantiate(cards[i], position.position, position.rotation);
}else{
Debug.Log("No more cards, but more positions need filling");
}
}
``````

I don’t use JS but this is what i could come up with

Link to shuffle on my blog:
http://mrmoss.net/2013/cunity3d-shuffling-an-array/

Thanks. I wasn’t familiar with list and C# isn’t a problem. I knew there was a trick with shuffling but kinda forgot I guess. Thanks.

Coroutine because if I could loop it I would’ve had it loop until it reached a number that wasn’t null. A long way to do it since it’s trial and error but it was the first solution that came it mind.

Just do this:

``````# a_list is just a list of all your cards
# sort the list randomly
a_list.Sort({x, y | return Random.Next(-1, 2)})
``````

Sort takes a function to let you write your own custom sorting routines. This routine takes 2 items and returns either -1, 0, or 1, depending if the first item is smaller, larger, or equal to the second item. If you instead ignore what the items are and return a random value of -1, 0, or 1, you’ve effectively shuffled the entire list.