Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by Leroterr · Dec 16, 2014 at 08:03 AM · c#randomfor-loopforeachrandomization

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!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by fafase · Dec 16, 2014 at 08:22 AM

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[i];
         array[i] = temp;
     }
     return array;
 }

 void Awake () 
 {
     Transform [] t = RandomChilds ();
     foreach (Transform tr in t) {
         print (tr.name);        
     }
 }
Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Kiwasi · Dec 16, 2014 at 08:35 AM 0
Share

Yup, that's pretty much what I was getting at. Deleted $$anonymous$$e because this is actually implementable.

avatar image fafase · Dec 16, 2014 at 09:40 AM 0
Share

Also, this is fairly hardcoded and could benefit some more general use by removing Transform and using generic. But I felt it might get overwhel$$anonymous$$g not knowing the OP level.

avatar image TooManySugar · Nov 19, 2016 at 06:07 PM 0
Share

nice trick!

avatar image yasssrenaeXD · May 19, 2018 at 05:42 PM 0
Share

Soooo ins$$anonymous$$d of a transform I changed it to a gameObject aaanndd there's this error:

error CS1579: foreach statement cannot operate on variables of type UnityEngine.GameObject' because it does not contain a definition for GetEnumerator' or is inaccessible

this is the line of code:

foreach(GameObject g in gameObject)

avatar image fafase yasssrenaeXD · May 23, 2018 at 01:40 PM 0
Share

This is because Transform implements IEnumerable interface to return children. GameObject does not as it would not have any suitable logic for implementation.

avatar image
1

Answer by zharik86 · Dec 16, 2014 at 08:17 AM

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by andrew-lukasik · May 19, 2018 at 10:43 PM

 List<Transform> transforms = new List<Transform>( gameObject.GetComponentsInChildren<Transform>() );
 transforms.Sort( (a,b)=> Random.Range(-10,11) );
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

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

Answers Answers and Comments

30 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

C# For loop in button to set gameObjects in array to active 1 Answer

Multiple Cars not working 1 Answer

foreach (or for-next loop) not updating local values 1 Answer

Converting foreach touch into for. 1 Answer

Distribute terrain in zones 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges