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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Setting list/array to specific value C#

Discussion in 'Scripting' started by ElnuDev, Apr 4, 2018.

  1. ElnuDev

    ElnuDev

    Joined:
    Sep 24, 2017
    Posts:
    298
    In Python, you can set a static list to a value like this:
    Code (Boo):
    1. my_list = [a, b, c]
    I can't seem to figure out how to do this in C#.
    Any ideas? Thanks!
     
  2. zoe_nightshade

    zoe_nightshade

    Joined:
    May 12, 2016
    Posts:
    27
    You can try this:
    Code (CSharp):
    1. // Declare list
    2. List <string> my_list = new List <string> ();
    3.  
    4. // Add values to list
    5. my_list.Add(a);
    6. my_list.Add(b);
    7. my_list.Add(c);
     
    ElnuDev likes this.
  3. ElnuDev

    ElnuDev

    Joined:
    Sep 24, 2017
    Posts:
    298
    Ah, okay. So it is impossible to create all values at once?
     
  4. ElnuDev

    ElnuDev

    Joined:
    Sep 24, 2017
    Posts:
    298
    I have quite a long list so this would be unpractical, :oops: although I'll keep that in mind for shorter lists. :)
     
  5. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    You can initialize the list with values like this:
    Code (CSharp):
    1. List<string> my_List = new List<string>()
    2. {
    3.     "Item1","Item2","Item3"
    4. };
     
    ElnuDev likes this.
  6. zoe_nightshade

    zoe_nightshade

    Joined:
    May 12, 2016
    Posts:
    27
    You could try this
    Code (CSharp):
    1. // Declare list
    2. string[] my_list;
    3.  
    4. // Add values to list
    5. my_list = new string [] {"value_1", "value_2", "value_3"};
    But if you want to make your list more dynamic, it's much preferable to use List.

    UPDATE: Is there a specific pattern on your values? You could probably try looping through it and let the loop add it in the list for you.
     
    ElnuDev likes this.
  7. ElnuDev

    ElnuDev

    Joined:
    Sep 24, 2017
    Posts:
    298
    Thank you!! :D Works like a charm.
     
  8. ElnuDev

    ElnuDev

    Joined:
    Sep 24, 2017
    Posts:
    298
    Thanks! No, there isn't a specific pattern. It is a large index of words.
     
  9. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Awesome.
     
  10. zoe_nightshade

    zoe_nightshade

    Joined:
    May 12, 2016
    Posts:
    27
    Maybe this can help. Goodluck on your project!
     
  11. ElnuDev

    ElnuDev

    Joined:
    Sep 24, 2017
    Posts:
    298
    Thanks for the link! It was quite helpful. :)