Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    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,744
    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,744
    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,744
    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.