Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct here to familiarize yourself with the rules and how to post constructively.

  2. Unity 2022.1 is now available as the latest Tech release.
    Dismiss Notice
  3. Improve your project's performance with our new guide on profiling in Unity.
    Dismiss Notice

How can i pick a rondom list from a Public list?

Discussion in 'Scripting' started by Jeremie-de-Vos, Apr 11, 2017.

  1. Jeremie-de-Vos

    Jeremie-de-Vos

    Joined:
    Jun 5, 2015
    Posts:
    120
    Hey,
    I want to get a rondom list and get the data from there.
    I can't find how i can do this.

    Code (CSharp):
    1.     public List<Tips> tips = new List<Tips>();
    2.     private void RandomTip()
    3.     {
    4.         string RandomString = tips[Random.Range(0, tips.Count - 1)];
    5.  
    6.         for (int i = 0; i < tips.Count; i++)
    7.         {
    8.             //Randomize te tip
    9.             //Change the text
    10.             //Change the color of the text
    11.         }
    12.     }
    13. }
    14. [System.Serializable]
    15. public class Tips
    16. {
    17.     public string Name;
    18.     public Color textColor;
    19. }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,658
    Make RandomString be of type Tips instead of string, and your Random.Range upper bound should NOT be - 1. (the int version of Random.Range is not inclusive on the upper bound, because it's intended for use in precisely this situation)

    From there, you don't need a for loop at all - you can just get at the data with RandomString.Name and RandomString.textColor.
     
  3. Jeremie-de-Vos

    Jeremie-de-Vos

    Joined:
    Jun 5, 2015
    Posts:
    120
    Thnx for your reply,
    I think i don;t really get the first part(
    New
    Make RandomString be of type Tips instead of string, and your Random.Range upper bound should NOT be - 1. (the int version of Random.Range is not inclusive on the upper bound, because it's intended for use in precisely this situation)
    )
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,658
    Make it "Tips RandomString" and not "string RandomString".
     
  5. Jeremie-de-Vos

    Jeremie-de-Vos

    Joined:
    Jun 5, 2015
    Posts:
    120
    This is what i have now: Tips RandomString = tips[Random.Range(0, tips.Count )];
     
  6. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,658
    Yep, that line looks correct now. So now you can use RandomString.textColor to get its color, etc
     
  7. Jeremie-de-Vos

    Jeremie-de-Vos

    Joined:
    Jun 5, 2015
    Posts:
    120
    Great, thank you so much!!! have a good day!;):)
     
    TaleOf4Gamers likes this.
unityunity