Foreach Statement Random Sequence/Order?

How do I randomize the sequence of items in a foreach statement?

Foreach iterates all the items inside a transform in an order.
Is there a way I can randomize that order?

For example:

Here’s the foreach statement that is NOT randomized:

foreach (Transform child in transform)
{
  Debug.Log(child);
}

Output:

child1

child2

child3

child4

What I want the output to be: (Randomized)

child4

child3

child1

child2

And yes. I know that even if it’s randomized, the first output could still happen. But I don’t want it to happen 100% of the time.


Is there a way I can do this? Thanks!

You cannot randomize a foreach because it internally uses the order of the collection. But you can randomize your collection priorly:

Transform [] RandomChilds()  // Here is a teaser for grammar nazis
{
	List<Transform> list = new List<Transform> ();
	foreach(Transform t in transform)
	{
		list.Add (t);
	}
	Transform [] array = list.ToArray ();
	for (int i = 0; i < list.Count; i++) 
	{
		int rand = Random.Range (0, list.Count);
		Transform temp = array[rand];
		array[rand] = array*;*

_ array = temp;_
* }*
* return array;*
* }*
* void Awake ()*
* {*
* Transform [] t = RandomChilds ();*
* foreach (Transform tr in t) {*
* print (tr.name); *
* }*
* }*

For example, you try this:

 void Start() {
  //Create list for state of child into transform and initialization
  List<int> tpChild = new List<int>; //maybe use bool list or array
  for(int i = 0; i < this.transform.childCount; i++) {
   tpChild.Add(i);
  }
  //Find random object
  for(int i = 0; i < this.transform.childCount; i++) {
   int num = Random.Range(0, tpChild.Count);
   Debug.Log(this.transform.GetChild(tpChild[num]));
   //Remove element from list
   tpChild.RemoveAt(num);
  }
 }

I hope that it will help you.

List transforms = new List( gameObject.GetComponentsInChildren() );
transforms.Sort( (a,b)=> Random.Range(-10,11) );